2017-10-26 14 views
-1

返されたJSONフィードからすべてのキーと値のペアを出力しようとしていますが、ログ時にはundefinedしか取得できません。ノードGETリクエストからJSONを解析する

サンプル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'

を、ファイル内のすべてのレコードについて。

+0

これは単なる間違いでした。申し訳ありませんが、私はそれを修正します。 – Colin747

答えて

2

「サンプルJSON」のJSONがURLの末尾のJSONと一致しません。

  1. JSONが無効です。うれしいことに、URLのJSONはOKです。
  2. JSONは単一のオブジェクトで構成されています。 URLのJSONはの配列で構成されています。

newString.entityidそれはそれ内のオブジェクトの単一のものであるかのようにあなたは、配列を処理しているためundefinedです。

最初に配列内のオブジェクトを1つ(または複数)選択する必要があります。

+0

'for'ループを使ってすべてのオブジェクトをループさせて、フィールドをすべて印刷することはできますか? – Colin747

+0

はい。これは、配列内のすべての項目に対して何かを行う通常の方法です。 – Quentin

+0

それは働いて、それは配列の感謝だったことを認識していない – Colin747

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を出力します。

関連する問題