【问题标题】:Accessing Data in JSON [Nodejs]以 JSON 格式访问数据 [Nodejs]
【发布时间】:2018-05-06 12:39:26
【问题描述】:

我有一些 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 不起作用。

【问题讨论】:

  • 这不是有效的 JSON。请提供您目前尝试过的代码。
  • @kern-elliott 你说 result.location 不起作用。您的意思是 results.location 不起作用吗?
  • @RobertMennell 感谢格式更改等,您的问题的答案是肯定的
  • @KernElliott 我已经更新了我的答案以反映模棱两可

标签: json node.js


【解决方案1】:

如果它是 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);

上面的打印位置到屏幕上。

【讨论】:

  • 好的,但是如果我不知道对象的密钥怎么办,那么我该如何访问该对象呢?这就是我使用数组的原因
  • 没有 JSON 对象这样的东西。它要么是 JS 对象,要么是 JSON。
  • 我不认为如果他们知道关键,这甚至会是一个问题
【解决方案2】:

对象的路径是results[0]['RANDOM STRING'].location,但是由于您不知道随机字符串,所以最好使用非引用方法来访问嵌套对象。

谢天谢地,最近版本的 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)

检查 Node Green 的 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。假设我想对每个帖子进行控制台记录(你真的永远不想这样做)

relatedPosts.forEach(console.log);

简单!


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

用户被定义为具有“first”、“last”、“location”键的对象

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

【讨论】:

    猜你喜欢
    • 2018-09-12
    • 1970-01-01
    • 1970-01-01
    • 2020-05-28
    • 2015-12-18
    • 1970-01-01
    • 2019-11-17
    • 1970-01-01
    • 2022-03-18
    相关资源
    最近更新 更多