如何将JSON转换为对象文字?

时间:2015-05-26 14:52:15

标签: javascript json object-literal

我以JSON的形式从源获取数据。让我们说JSON看起来像这样

var data = [
   {"city" : "Bangalore", "population" : "2460832"}
]

我将此数据对象传递到kendo网格中,并且我将使用其开箱即用的功能来格式化数字。所以,我需要与看起来像这个

的对象文字相同的JSON
var data = [{city : "Bangalore", population: 2460832}]

是否有任何库,功能或简单方法来实现这一目标?

2 个答案:

答案 0 :(得分:2)

您可以iterate over the Objects in the Array修改每个population属性,将其值从字符串转换为parseInt() or similar的数字:

var data = [
    {"city" : "Bangalore", "population" : "2460832"}
];

data.forEach(function (entry) {
    entry.population = parseInt(entry.population, 10);
});

console.log(data[0].population);        // 2460832
console.log(typeof data[0].population); // 'number'

答案 1 :(得分:0)

您可以按照以下想法将JSON转换为对象文字:

(function() { 

  var json = 
   [
    {
      "id": 101,
      "title": 'title 1'
    }, 
    {
      "id": 103,
      "title": 'title 3'
    },
    {
      "id": 104,
      "title": 'title 4'
    }
  ];

  var result = {};  

  for (var key in json) {
    var json_temp = {} 
    json_temp.title = json[key].title;
    result[json[key].id] = json_temp;
  }

  console.log(result);

})();

输出将是:

Object {
  101: Object {
     title: "title 1" 
  }
  102: Object {
     title: "title 2" 
  }
  103: Object {
     title: "title 3" 
  }
}
相关问题