【问题标题】:Extract JSON field from JSON data in Node.js从 Node.js 中的 JSON 数据中提取 JSON 字段
【发布时间】:2016-04-11 20:09:11
【问题描述】:

您好,我有一个名为 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 字符串。 JSON 要求每个键都用双引号引起来。 (即{ foo: "bar" } 坏,{ "foo": "bar" } 好)。
  • 好的。那么有什么解决方法吗?
  • 好:修复你的 JSON 文件。不好:var jsonContent = eval(body)。 (但location: [Object] 可能不会做你想做的事......)
  • 你确定 JSON 是一个字符串吗?对我来说,它看起来像是来自 console.log 的东西
  • 我该如何解决这个问题?

标签: javascript json node.js npm


【解决方案1】:

如果您从 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);
});

【讨论】:

    猜你喜欢
    • 2015-09-30
    • 2023-03-04
    • 2020-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多