从Node.js中的JSON数据中提取JSON字段

Extract JSON field from JSON data in Node.js

本文关键字:JSON 提取 字段 数据 js 中的 Node      更新时间:2024-05-06

Hi我有一个名为body的JSON字符串,包含以下内容:

[ { _index: 'domain', _type: 'tweets', _id: 'AVQDcXJkNcXkyWvNoI-S', _score: 1.3844389, _source: { username: 'rosscmary@gmail.com', 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] } } ]

我想从这个文件中提取每个text字段,并将其记录到控制台

现在我正在这样做:

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

但它不起作用。

有人能帮我吗?我正在使用node js,并且一直被困在这个节点上。

如果您从json字符串格式的对象开始,这里有一个完整的解决方案

var jsonString = "[{'"_index'":'"domain'",'"_type'":'"tweets'",'"_id'":'"AVQDcXJkNcXkyWvNoI-S'",'"_score'":1.3844389,'"_source'":{'"username'":'"rosscmary@gmail.com'",'"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);
});