如何将JSO转换为JSON?

时间:2015-09-03 10:20:54

标签: javascript json

我有例子:

var data = [{"name":"eric","age":"24"},{"name":"goulding","age":"23"}]

我想将上面的jso转换为json,就像这样的结果:

[{name:"eric",age:24},{name:"goulding",age:23}]

请给我建议。

1 个答案:

答案 0 :(得分:2)

您需要将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格式的数组对象。