How to convert JSO to JSON?

I have an example:

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

I want to convert jso above to json, like this result:

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

Please give me some advice.

+4
source share
1 answer

You need to use JSON.parse with the reviver parameter:

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);

When reviver is called with reviver("name", "eric"), it returns "eric"because it "eric"cannot be converted to a number. However, when called with reviver("age", "24"), the number is returned 24.

Meanwhile, as others have already noted, the literal [{"name":"eric","age":"24"},{"name":"goulding","age":"23"}]is not JSON, it is an array. But the string '[{"name":"eric","age":"24"},{"name":"goulding","age":"23"}]'is a valid array object in JSON format.

+2

Source: https://habr.com/ru/post/1605711/


All Articles