如何在javascript中构造对象以获得预期的JSON

时间:2017-04-13 23:43:11

标签: javascript json

对象是:

 people[resident1:[
     "name" : "valueForName",
     "address" : "valueForAddress",
     "city"  : "valueForCity"
],
resident2:[
     "name" : "valueForName",
     "address" : "valueForAddress",
     "city"  : "valueForCity"
]]

人们有多个居民,我想要一个具有以下结构的JSON:

"residents" :{
    "valueForName1":"valueForCity1",
    "valueForName2":"valueForCity2"
}

有人可以帮忙吗?我是javascript的新手。谢谢!

2 个答案:

答案 0 :(得分:2)

你应该有一个包含对象的数组:

{
  "residents": [{
    "name": "valueForName1",
    "address": "valueForAddress1",
    "city": "valueForCity1"
  }, {
    "name": "valueForName2",
    "address": "valueForAddress2",
    "city": "valueForCity2"
  }]
}

答案 1 :(得分:1)

你可以这样做,

var result = {};
var residents = [];
var resident1 = {};
var resident2 = {};

resident1.name = "Joe";
resident1.address = "street1";
resident1.city = "Boston";

resident2.name = "Smith";
resident2.address = "street2";
resident2.city = "New York";

residents.push(resident1);
residents.push(resident2);

result.residents = residents;

console.log(JSON.stringify(result));

打印在

下面
{
  "residents": [
    {
      "name": "Joe",
      "address": "street1",
      "city": "Boston"
    },
    {
      "name": "Smith",
      "address": "street2",
      "city": "New York"
    }
  ]
}