向JSON文档添加元素

dlyk1988

我已经在代码中初始化了一个JSON文档,如下所示:

var json = [];

我使用'.push()'方法向此文档中添加元素,如下所示:

json.push({title: "abc", link: "xxx"});

最后,我得到一个看起来像这样的JSON文档:

[
  {
    "title": "abc",
    "link": "xxx"
  }
  {
    "title": "asd",
    "link": "zzz"
  }
  ...
]

这并不完全不好,但是我希望它看起来像这样:

{
  "links":
    [
      {
        "title": "abc",
        "link": "xxx"
      }
      {
        "title": "asd",
        "link": "zzz"
      }
      ...
    ]
}

有什么想法可以做到吗?

巴特

通过做

var json = [];

您初始化一个数组,而不是一个对象。

要拥有一个对象,您可以执行以下操作:

var json = {};

然后添加一个字段:

json.links = [];

然后向您推送链接对象:

json.links.push({title: "abc", link: "xxx"});

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章