在JSON [Nodejs]中访问数据

时间:2017-11-22 17:10:42

标签: json node.js

我有一些JSON,当转换为Object时,它看起来如下:

{ 'SOME RANDOM STRING': { 'Article Headline': 'headline', 'Article Image URL': 'image url', 'Article Published Date': 'date', 'Article URL': 'article url', 'Category': 'mental illness,', 'Location': 'place', 'Source Name': 'source' } }

我把它存储在一个名为results的数组中。我如何才能访问Location中的值,因为result.location不起作用。

2 个答案:

答案 0 :(得分:0)

如果是JSON,则不必将其转换为数组。你可以直接解析它,如下所示。

var obj = {
'-KzZaDXhWRwdzfKUf5tl':
{ 'Article Headline': 'headline',
  'Article Image URL': 'image url',
  'Article Published Date': 'date',
  'Article URL': 'article url',
  'Category': 'mental illness,',
  'Location': 'place',
  'Source Name': 'source' }

}

console.log(obj['-KzZaDXhWRwdzfKUf5tl'].Location);

以上打印件放置在屏幕上。

答案 1 :(得分:0)

对象的路径为results[0]['RANDOM STRING'].location,但由于您不了解RANDOM STRING,因此最好使用非参照方法来访问嵌套对象。

值得庆幸的是,最近版本的NodeJS / Javascript中有很多工具可以做到这一点!

Array.prototype.map(function(item, index, array), context)似乎就像你想要的功能!它将根据应用于数组中每个事物的函数返回创建一个新数组。

然后,您可以使用构建在对象本身上的其他工具(如

)来更改每个对象
// array of keys, useful for looking for a specific key
Object.keys(someReallyObtuseObject)

// array of VALUES! Awesome for looking for a specific data type
Object.values(someReallyObtuseObject)

检查节点绿色表示Object.values显示它在NodeJS 7.10或更高版本中可用,而Object.keys显示它可用于4.8.6!

不要忘记这些将对象转换为数组。之后,您可以使用forEach,filter,map和许多其他数组方法来访问数据!

示例

假设我有一个名为results

的数据库中的数组
const results = [{...},{...},...];

我想找到一个带有我知道的标识符的结果

// I will either find the result, or receive undefined
let result = results.filter(r => r[key] == identifier)[0];

但是在我的结果中,该对象有一个名为"相关帖子"它是一个对象,其中一个键是每个相关帖子的唯一ID。我想访问所说的帖子,但我不知道他们的唯一ID,因此我想将其转换为数组以便于处理

// This gives me an array of related posts with their ID now nested inside them
let relatedPosts = Object.keys(result['related posts']).map(k => {
  let r = result['related posts'][k];
  r.id = k;
  return r;
});

现在我可以轻松浏览相关帖子了,我从来不知道帖子的ID。让我们说我想在每个帖子上安装console.log(你真的不想这样做)

relatedPosts.forEach(console.log);

容易!

示例2,从用户数组中获取位置

用户被定义为一个带有键的对象' first',' last',' location'

const users = [{...},{...},...]
let locations = users.map(user => user.location)