Convert JSON string to JSON object

Method to convert json string to json object. In the process of data transmission, json is transmitted in the form of text or string, while JS operates on JSON objects (which can be called like objects such as obj.name), so the mutual conversion between JSON objects and JSON strings is the key.


E.g:

JSON字符串:
var str1 = '{ "name": "cxh", "sex": "man" }'; //规则     
var str1 = '{ name: "cxh", "sex": "man" }'; //随意JSON对象:var str2 = { "name": "cxh", "sex": "man" };

1. Convert JSON string to JSON object

        var res = '{ "name": "ls", "age": 10 }';
        var json1 = eval('(' + res + ')') ;//ie8 (compatibility mode), ie7 and ie6 can also use eval() to convert strings to JSON objects, but these methods are not recommended, this method Unsafe eval will execute the expression in the json string
        //var json2 = res1.parseJSON();//I tested and reported an error, and I checked the data and said that the version of the json package is too low
        var json3 = JSON.parse(res) ;//Name must be enclosed in quotation marks, otherwise invalid characters will be reported, eval means optional
        var json4 = $.parseJSON(res) ;//jQueyr package, quotes must be added outside the name, otherwise invalid characters will be reported


Special Note: If obj is originally a JSON object, then it will still be a JSON object after conversion using the eval() function (even if it is converted multiple times), but there will be a problem (throwing a syntax exception) after processing it using the parseJSON() function.

2. Convert JSON object to JSON string

        var json = { "name": "ls", age: 10 };
        //var res1 = json.toJSONString();//// I tested and reported an error, and the data found that the version of the json package is too low
        var res2 = JSON.stringify(json) ;//There is no problem with quotation marks outside the name

Notice:

Among the above methods, except for the eval() function that comes with js, the other methods come from the json.js package. The new version of JSON modifies the API, injecting both JSON.stringify() and JSON.parse() methods into Javascript's built-in objects, the former becomes Object.toJSONString(), and the latter becomes String. parseJSON(). If it prompts that the toJSONString() and parseJSON() methods cannot be found, your json package version is too low.


3. Backend returns JSON

1. Return the json string return content(jsonStr);

2. Return the json object return JSON( new { state = 0, msg = " Username does not exist " } );

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325897664&siteId=291194637