【问题标题】:Nodejs how to use map of object?Nodejs如何使用对象映射?
【发布时间】:2015-12-08 20:55:52
【问题描述】:

你好,我有一个像这样的 json,叫做 body:

{
  data: {
    id:1,
    name:hallo
  },
  paging: {
    cursors: {
      next: "abc"
    }
  }
}

所以我必须将它保存到地图中,然后我需要打印或修改它。 如果我用这段代码保存它

var Map = require("collections/map");

var new_body = JSON.parse(body)
var map = new Map(new_body);

我在打印时遇到了一些困难,例如 map.paging.cursor.next,我该怎么办?也许我必须在将 json 插入其中之前定义该映射的结构,我不知道...

【问题讨论】:

  • 你的意思是map.paging.cursors? (带 s)。这也是无效的 JSON,键必须是字符串,并且字符串必须用双引号引起来。使用 jsonlint.com 检查 JSON 是否有效

标签: json node.js dictionary hashmap


【解决方案1】:

您的 json 有错误。像这样更正它们。

{
  "data": {
    "id": 1,
    "name": "hallo"
  },
  "paging": {
    "cursors": {
      "next": "abc"
    }
  }
}

然后可以这样解析json,得到paging.cursors.next的值。

var map = JSON.parse(body);//This will parse the json string

现在map.paging.cursors.next 的值将是"abc"

【讨论】:

  • 我已经完成了,但现在它给了我这个错误:调试:内部,实现,错误类型错误:无法读取未定义的属性“游标”。和更改前给我的一样,它只读取 paging like key 然后 cursors.next like 和 object....
  • 我在发帖之前对其进行了测试,它确实有效。你能把你的代码贴出来让我检查一下吗?
  • 谢谢你现在它工作我写了:console.log(map.get(paging)) 但正确的代码是console.log(map.get("paging"))。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-18
  • 2014-11-02
  • 1970-01-01
  • 2019-09-24
相关资源
最近更新 更多