从JSON API获取JSON对象?

时间:2019-11-05 08:04:12

标签: node.js json

我正在尝试从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 变量时,它显示为“ 未定义”。

2 个答案:

答案 0 :(得分:1)

不确定您实际上要获取的数据是什么,但是如果要进行api调用并以express形式呈现结果,则代码应如下所示:

var express = require('express');
var request = require('request');
var app = express();

app.get('/', function (req, res) {
    var reg = 'Dhaka';
    request('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', function (error, response, body) {
        // parse JSON so we have an object to work with
        var weather = JSON.parse(body).data.weather;
        // send data to browser
        res.send(weather);
    });
});

// Run express server on port 3000
app.listen(3000, function () {
    console.log('Example app listening on port 3000!');
});

答案 1 :(得分:0)

您应该从jpar变量获取数据,而不是从bodydata

获取数据
let jpar = JSON.parse (bodydata)
datab = jpar.data
console.log(datab)