piyush121
piyush121

Reputation: 515

Extract JSON field from JSON data in Node.js

Hi I have a JSON string named body with following contents:

[ { _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] } } ]

I want to extract every text field from this file and log it to the console.

Right now I am doing this :

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

But it's not working.

Can any body help me with this ? I am using node js and been stuck on this one.

Upvotes: 0

Views: 2460

Answers (1)

Borja Tur
Borja Tur

Reputation: 817

Here a complete solution if you start with your object 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);
});

Upvotes: 1

Related Questions