无法解析在mLAB上托管的MongoDB的Json响应

时间:2018-01-18 02:59:54

标签: json node.js mongodb api mlab

我有一份文件说汽车在mLAB上托管。当我使用mLAB API执行汽车的GET请求时,我收到以下响应:

>     [ { "_id" : { "$oid" : "5a5e381c734d1d347184ed9d"} , "car_ID" : "1122" , "car_location_latitude" : "14.764976" ,
> "car_location_longitude" : "13.543345" , "s1" : "" , "s2" : "" , "s3"
> : "966" , "s4" : "" , "s5" : "" , "m1" : "" , "m2" : "" , "m3" : "" ,
> "l1" : "" , "l2" : ""} , { "_id" : { "$oid" :
> "5a5e383a734d1d347184edb4"} , "car_ID" : "1234" ,
> "car_location_latitude" : "12.975715" , "car_location_longitude" :
> "77.572836" , "s1" : "" , "s2" : "" , "s3" : "" , "s4" : "" , "s5" :
> "" , "m1" : "567" , "m2" : "" , "m3" : "" , "l1" : "" , "l2" : ""} ]

NodeJS代码:从我调用mLAB的API调用代码片段。

Display Requests
app.get('/..../requests',function(req,res){

    var id=req.params.deliveryID;
    var result="";
    function second()
    {
    return res.status(200).send('{ \"data\":{\"type":\"text\",\"text\":\"'+result+'\"}}');
    }

    function first(callback)
    {

    request('https://api.mlab.com/api/1/databases/.................', function (error, response, body) {
    if (!error && response.statusCode == 200) 
    {

        console.log("---->"+body+"-----");
        result=body;
        var o=JSON.parse(body);

        //Now using variable o, how can I access JSON Keys car_ID etc

        callback(second);
    }
    });

    }
    first(second);


});

1 个答案:

答案 0 :(得分:1)

find返回cars是一个对象数组,你可以简单地迭代对象并访问它的元素

汽车阵列响应

var cars = [
        { "_id" : "5a5e381c734d1d347184ed9d" , "car_ID" : "1122" , "car_location_latitude" : "14.764976" ,            "car_location_longitude" : "13.543345" , "s1" : "" , "s2" : "" , "s3"            : "966" , "s4" : "" , "s5" : "" , "m1" : "" , "m2" : "" , "m3" : "" ,            "l1" : "" , "l2" : ""        } , 
        { "_id" : "5a5e383a734d1d347184edb4" , "car_ID" : "1234" , "car_location_latitude" : "12.975715" , "car_location_longitude" : "77.572836" , "s1" : "" , "s2" : "" , "s3" : "" , "s4" : "" , "s5" : "" , "m1" : "567" , "m2" : "" , "m3" : "" , "l1" : "" , "l2" : ""
 } 
 ]

迭代

for (var car of cars){
    console.log(car.car_ID)
}

输出

saravana@ubuntu:~/node-mongoose$ node so5.js
1122
1234
saravana@ubuntu:~/node-mongoose$

如果响应是一个字符串的json数组,那么你需要解析和迭代

var carsArray = JSON.parse(body);
for (var i = 0; i < carsArray.length; i++){
    var car = carsArray[i];
    console.log(car.car_ID)
}