修改JSON对象

时间:2015-04-01 22:21:10

标签: javascript arrays json

我有一个由Papa Parse从CSV文件生成的JSON,如下所示:

{ object, object, object, .... , object }

我需要修改它,看起来像这样:

{ "publication" : 
    {
      "id" : 1,
      "name" : "name1"
    },
  "publication" :
    {
      "id" : 2,
      "name" : "name2"
    },
  "publication" :
    {
      "id" : 3,
      "name" : "name3"
    }
}

“id”和“name”是每个对象中的属性。

换句话说,我需要一个说“发布”的JSON,并且每个“发布”事件都在其下面嵌套了上述一个对象的属性名称和值。

我怎样才能通过Javascript实现这一目标?

谢谢

3 个答案:

答案 0 :(得分:2)

你不能放多个同名的钥匙......

它放在数组中的解决方案

{ 
    "publication" : [
      {
        "id" : 1,
        "name" : "name1"
      },
      {
        "id" : 2,
        "name" : "name2"
      },
      {
        "id" : 3,
        "name" : "name3"
      }]
}

答案 1 :(得分:1)

这不是一系列出版物吗?

   { publications: [{"id":1, "name":"name1"},
         {"id":2, "name":"name2"}.....]}

答案 2 :(得分:1)

如果我理解正确,你可能意味着你有这样的对象:

{"publication" : { "id" : 1, "name" : "name1" }
{"publication" : { "id" : 2, "name" : "name2" }
{"publication" : { "id" : 3, "name" : "name3" }

您可以做些什么来获得:

{ "publication" : [ 
    {
        "id" : 1, 
        "name" : "name1"
    }, 
    {
        "id" : 1, 
        "name" : "name2"
    }, 
    {
        "id" : 3, 
        "name" : "name3"
    } ] 
}

是:

var json = [{"publication" : { "id" : 1, "name" : "name1" }},
                {"publication" : { "id" : 2, "name" : "name2" }},
                {"publication" : { "id" : 3, "name" : "name3" }}];

var newJson = {"publication" : []};

    var i = 0;
    for (var item in json) {
        var key = json[item];
        var obj = {"id" : key["publication"]["id"], "name" : key["publication"]["name"]};
        newJson["publication"][i] = obj;
        i++;
    }

如果你想打印"漂亮":

,你可以检查一下

How can I pretty-print JSON using JavaScript?