从Node GET请求中解析JSON

时间:2017-10-26 10:36:50

标签: javascript json node.js

我正在尝试从返回的JSON Feed中输出所有键/值对,但我只是在记录时获得undefined

示例JSON:

{ entityname: 'INTERNET SOLUTIONS INC, Delinquent June 1, 2014',
    entityid: '20131032920',
    agentfirstname: 'MARTIN',
    entitystatus: 'Delinquent',
    agentprincipalcountry: 'US',
    agentprincipaladdress1: '10955 WESTMOOR DR.',
    entitytypeverbatim: 'Corporation',
    principalcountry: 'US',
    agentprincipalstate: 'CO',
    agentprincipalcity: 'WESTMINSTER',
    principaladdress1: '608 CENTER DR.',
    agentlastname: 'PELMORE',
    principalcity: 'Los Angeles',
    entityformdate: '2013-01-16T00:00:00',
    agentprincipalzipcode: '80021',
    principalstate: 'CA',
    entitytype: 'DPC',
    principalzipcode: '90045' }

我正试图使用​​的代码:

const http = require('http');

http.get('http://data.colorado.gov/resource/4ykn-tg5h.json', function(res) {
    console.log('statusCode:', res.statusCode);
    console.log('headers:', res.headers);
    var body = "";
    var newString = "";

    res.on('data', function(d) {
        body += d.toString();   
    });

    res.on('end', function() {
        newString = JSON.parse(body);
        console.log('output', newString.entityid);
    });

}).on('error', function(e) {
    console.error(e);
});

我的预期输出是:

entityid: '20131032920'

对于文件中的每条记录。

2 个答案:

答案 0 :(得分:2)

您的"示例JSON中的JSON"与URL末尾的JSON不匹配。

  1. 您的JSON无效。令人高兴的是,URL上的JSON看起来还不错。
  2. 您的JSON由单个对象组成。 URL中的JSON由类似对象的数组组成。
  3. newString.entityidundefined,因为您将数组视为其中的单个对象。

    您需要先在数组中选择一个(或多个)对象。

答案 1 :(得分:0)

您的在线json实际上是一个包含多个对象的数组。您需要选择或迭代数组的元素。

例如:

const http = require('http');

http.get('http://data.colorado.gov/resource/4ykn-tg5h.json', function(res) {
    console.log('statusCode:', res.statusCode);
    console.log('headers:', res.headers);
    var body = "";
    var newString = "";

    res.on('data', function(d) {
        body += d.toString();   
    });

    res.on('end', function() {
        newAry = JSON.parse(body);
        // Here the modified code, we loop across the whole JSON array.
        newAry.forEach((e) => { console.log('output', e.entityname); })
    });

}).on('error', function(e) {
    console.error(e);
});

将打印出所有entityname s。