如何将 JSON 转换为对象字面量?
How do I convert a JSON to an object literal?
我以 JSON 的形式从来源获取数据。假设 JSON 看起来像这样
var data = [
{"city" : "Bangalore", "population" : "2460832"}
]
我会将此数据对象传递到 kendo 网格中,并且我将使用其开箱即用的功能来格式化数字。所以,我需要与对象文字相同的 JSON,看起来像这样
var data = [{city : "Bangalore", population: 2460832}]
是否有任何库、函数或简单的方法可以实现此目的?
你可以iterate over the Object
s in the Array
and modify each population
property, converting its value from a string to a number with 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'
您可以按照以下思路将 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"
}
}
我以 JSON 的形式从来源获取数据。假设 JSON 看起来像这样
var data = [
{"city" : "Bangalore", "population" : "2460832"}
]
我会将此数据对象传递到 kendo 网格中,并且我将使用其开箱即用的功能来格式化数字。所以,我需要与对象文字相同的 JSON,看起来像这样
var data = [{city : "Bangalore", population: 2460832}]
是否有任何库、函数或简单的方法可以实现此目的?
你可以iterate over the Object
s in the Array
and modify each population
property, converting its value from a string to a number with 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'
您可以按照以下思路将 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"
}
}