如何解析这个json对象?

时间:2015-10-28 19:49:39

标签: arrays json node.js parsing

这是JSON对象,我需要访问 gps-recs :条目。短划线( - )给我和我在尝试解析时未定义的错误:

"recs-count": 139, 
"gps-recs": [
    { 
        "RecId": 40020551513, 
        "City": "New Port Richey", 
        "Country": "USA", 
        "County": "PASCO", 
        "State": "FL", 
        "Street": "1546 Amaryllis ct.", 
        "ZipCode": "34655", 
        "CurrentOdometer": 12161, 
        "Heading": 0, 
        "Latitude": 28.181690, 
        "Longitude": -82.658420, 
        "SpeedMph": 0, 
        "SpeedLimitMph": 25, 
        "Status": "Stopped", 
        "StatusDuration": "1.05:00:00", 
        "PrimaryLandmarkName": "Max's home", 
        "CurrentHardmountEvent": null, 
        "UtcTimeTag": "2013-11-28T05:23:34", 
        "UserTimeTag": "2013-11-28T00:23:34", 
        "UserInfo": { 
            "UserId": 201274, 
            "UserNumber": "22", 
            "UserName": "Max's Car" 
        } 
    },
    { 
        "RecId": 40020551610, 
        "City": "New Port Richey", 
        "Country": "USA", 
        "County": "PASCO", 
        "State": "FL", 
        "Street": "1546 Amaryllis ct.", 
        "ZipCode": "34655", 
        "CurrentOdometer": 12161, 
        "Heading": 0, 
        "Latitude": 28.181690, 
        "Longitude": -82.658410, 

这是我的代码:

var request = require("request");

var options = { method: 'GET',
  url: 'URL',
   };

request(options, function (error, response, body) {
  if (error) throw new Error(error);
  var result = JSON.parse(body);
    console.log(result);
    console.log(Object.keys(result).length);
    });

我试图用来解析gps-recs条目中的部分的parse语句是:

var result = JSON.parse(body).gps-recs;

我收到以下错误消息: ReferenceError:未定义recs

1 个答案:

答案 0 :(得分:0)

您可以像data["gps-recs"]

那样访问

您应该更新以下代码:

request(options, function (error, response, body) {
  if (error) throw new Error(error);
  var result = JSON.parse(body);
  console.log(result["gps-recs"]);
  console.log(result["gps-recs"].length);
});