Nodejs訪問網(wǎng)絡并解析返回的json的實現(xiàn)方法
一:解析本地Json文件
sample.json
{
"api": "mtop.common.getTimestamp",
"v": "*",
"ret": [
"SUCCESS::接口調(diào)用成功"
],
"data": {
"t": "1647006040138"
}
}jsonParse.js:
// 引入文件系統(tǒng)模塊
var fs = require('fs');
// 讀取文件sample.json文件
fs.readFile('sample.json',
// 讀取文件完成時調(diào)用的回調(diào)函數(shù)
function(err, data) {
// json數(shù)據(jù)
var jsonData = data;
// 解析json
var jsonParsed = JSON.parse(jsonData);
// 訪問元素
console.log(jsonParsed.data.t);
});二:訪問網(wǎng)絡
我們拿免費的獲取服務端時間為例:訪問接口如下:http://api.m.taobao.com/rest/api3.do?api=mtop.common.getTimestamp
在postman中模擬下請求:

這個請求體的參數(shù)key:api,value是 mtop.common.getTimestamp
我們利用request庫進行post的網(wǎng)絡請求,首先安裝下這個request庫:
使用命令,將庫安裝即可
npm install request --save -dev
網(wǎng)絡請求如下 :
var request = require('request');
request.post({url:'http://api.m.taobao.com/rest/api3.do?api=mtop.common.getTimestamp', form:{
"api": "mtop.common.getTimestamp",
}}, function(error, response, body) {
//console.log(error,response,body)
console.log(body)
})執(zhí)行該js文件,可以看到成功獲取到時間body的返回值:

Json如下:
{ "api": "mtop.common.getTimestamp", "v": "*", "ret": [ "SUCCESS::接口調(diào)用成功" ], "data": { "t": "1647006040138" }}最后我們把解析json的代碼也補充上,就可以獲取到我們需要的服務器時間毫秒值了:
var request = require('request');
request.post({url:'http://api.m.taobao.com/rest/api3.do?api=mtop.common.getTimestamp', form:{
"api": "mtop.common.getTimestamp",
}}, function(error, response, body) {
//console.log(error,response,body)
console.log(body)
// 解析json
var jsonParsed = JSON.parse(body);
// 訪問元素
console.log(jsonParsed.data.t);
})到此這篇關于Nodejs訪問網(wǎng)絡并解析返回的json的實現(xiàn)方法的文章就介紹到這了,更多相關Node訪問網(wǎng)絡并返回json內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
node.js中的fs.createReadStream方法使用說明
這篇文章主要介紹了node.js中的fs.createReadStream方法使用說明,本文介紹了fs.createReadStream方法說明、語法、接收參數(shù)、使用實例和實現(xiàn)源碼,需要的朋友可以參考下2014-12-12
node.js使用免費的阿里云ip查詢獲取ip所在地【推薦】
這篇文章主要介紹了node.js使用免費的阿里云ip查詢獲取ip所在地的相關知識,非常不錯,具有一定的參考借鑒價值 ,需要的朋友可以參考下2018-09-09
詳解Node.js amqplib 連接 Rabbit MQ最佳實踐
這篇文章主要介紹了詳解Node.js amqplib 連接 Rabbit MQ最佳實踐,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-01-01

