我正在尝试从JSON文件中获取JSON对象,它具有嵌套的JSON对象(也具有数组)。因此,我如何解析它并使用NODEJS获得单个元素和对象。
我尝试过此
const express = require('express');
const app = express();
const request = require("request");
reg = "Dhaka"
link = 'https://api.worldweatheronline.com/premium/v1/weather.ashx?key=ca926a35ffc14b97b0993747192010&q='+reg+'&format=json&num_of_days=5&extra=localObsTime&date=today&fx=yes&cc=yes&fx24=yes&includelocation=yes&tp=3'
let bodydata = "";
request (link, function (error, response, body) {
console.log('error:', error);
console.log('statusCode:', response && response.statusCode);
// console.log('body:', body); // Print the HTML for the Google homepage.
bodydata = body
// console.log (bodydata)
let jpar = JSON.parse (bodydata)
datab = bodydata.data
console.log(jpar)
});
这是输出。
error: null
statusCode: 200
{ data:
{ request: [ [Object] ],
nearest_area: [ [Object] ],
current_condition: [ [Object] ],
weather: [ [Object] ],
ClimateAverages: [ [Object] ] } }
正在获取响应,但是当我尝试打印datab变量时,它显示为“ undefined”。
您应该从jpar
变量而不是bodydata
中获取数据>
let jpar = JSON.parse (bodydata)
datab = jpar.data
console.log(datab)
[不确定您实际要获取的数据,但是如果您要进行api调用并以快速方式呈现结果,则您的代码应如下所示: