我有一个例子:
var data = [{"name":"eric","age":"24"},{"name":"goulding","age":"23"}]
我想将上面的jso转换为json,就像这样的结果:
[{name:"eric",age:24},{name:"goulding",age:23}]
请给我建议.
最佳答案 您需要将
JSON.parse与reviver参数一起使用:
var jsonString = '[{"name":"eric","age":"24"},{"name":"goulding","age":"23"}]';
// given a string value, returns the number representation
// if possible, else returns the original value
var reviver = function (key, value) {
var number = Number(value);
return number === number ? number : value;
};
// because the reviver parameter is provided,
// the parse process will call it for each key-value pair
// in order to determine the ultimate value in a set
var data = JSON.parse(jsonString, reviver);
当使用reviver(“name”,“eric”)调用reviver时,它返回“eric”,因为“eric”无法转换为数字.但是当使用reviver(“age”,“24”)调用时,返回数字24.
同时,正如其他人已经注意到文字[{“name”:“eric”,“age”:“24”},{“name”:“goulding”,“age”:“23”}]不是JSON,它是一个数组.但字符串'[{“name”:“eric”,“age”:“24”},{“name”:“goulding”,“age”:“23”}]’表示有效的JSON格式的数组对象.