2016-04-11 23 views
0

Hallo, ich habe eine Zeichenfolge JSON body mit folgendem Inhalt benannt:Extract JSON Feld von JSON-Daten in Node.js

[ { _index: 'domain', _type: 'tweets', _id: 'AVQDcXJkNcXkyWvNoI-S', _score: 1.3844389, _source: { username: '[email protected]', text: '@amrightnow Go Trump Go Trump Go Trump', location: [Object] } }, { _index: 'domain', _type: 'tweets', _id: 'AVQDe5CONcXkyWvNoI_G', _score: 0.98909086, _source: { username: 'Trump Hotels Jobs', text: '#Vancouver, BC#CustomerService #Job: Reservations Agent at Trump ', location: [Object] } }, { _index: 'domain', _type: 'tweets', _id: 'AVQDfDpfNcXkyWvNoI_L', _score: 0.5487978, _source: { username: '☩Chaunce☩', text: 'While figuring out what 2 do next, #Trump complains 2 his rep about not winning a "popcorn" it seems he\'ll go after the #MTVMovieAwards too', location: [Object] } } ]

Ich mag jedes text Feld aus dieser Datei extrahieren und sie in dem Protokoll Konsole.

Im Moment habe ich dies tue:

var jsonContent = JSON.parse(body); jsonContent = JSON.parse(JSON.stringify(jsonContent)); console.log(jsonContent);

Aber es funktioniert nicht.

Kann mir irgendein Körper dabei helfen? Ich benutze Knoten js und bin auf diesem festgefahren.

+0

Dieser Start ist kein gültiger JSON-String. JSON erfordert, dass jeder Schlüssel doppelt zitiert wird. (d. h. '{foo:" bar "}' bad, '{" foo ":" bar "}' gut). – Amadan

+0

okay. Also irgendwelche Arbeiten herum? – piyush121

+0

Gut: Repariere deine JSON-Datei. Schlecht: 'var jsonContent = eval (body)'. (Aber 'location: [Object]' wird wahrscheinlich nicht das tun, was Sie wollen ...) – Amadan

Antwort

0

die komplette Lösung, wenn Sie mit Ihrem Objekt in JSON-String-Format

var jsonString = "[{\"_index\":\"domain\",\"_type\":\"tweets\",\"_id\":\"AVQDcXJkNcXkyWvNoI-S\",\"_score\":1.3844389,\"_source\":{\"username\":\"[email protected]\",\"text\":\"@amrightnow Go Trump Go Trump Go Trump\",\"location\":[null]}},{\"_index\":\"domain\",\"_type\":\"tweets\",\"_id\":\"AVQDe5CONcXkyWvNoI_G\",\"_score\":0.98909086,\"_source\":{\"username\":\"Trump Hotels Jobs\",\"text\":\"#Vancouver, BC#CustomerService #Job: Reservations Agent at Trump \",\"location\":[null]}},{\"_index\":\"domain\",\"_type\":\"tweets\",\"_id\":\"AVQDfDpfNcXkyWvNoI_L\",\"_score\":0.5487978,\"_source\":{\"username\":\"☩Chaunce☩\",\"text\":\"While figuring out what 2 do next, #Trump complains 2 his rep about not winning a \\\"popcorn\\\" it seems he'll go after the #MTVMovieAwards too\",\"location\":[null]}}]"; 
 

 
var jsonObj = JSON.parse(jsonString); 
 

 
jsonObj.map((elt) => { 
 
    console.log(elt["_source"].text); 
 
});