The content of this article is to introduce the method of converting json strings into json objects using js. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
JSON string:
var str1 = '{ "name": "cxh", "sex": "man" }';
JSON object:
var str2 = { "name": "cxh", "sex": "man" };
1. Convert JSON string toJSON Object
To use the above str1, you must first convert it into a JSON object using the following method:
//由JSON字符串转换为JSON对象 var obj = eval('(' + str + ')');
or
var obj = str.parseJSON(); //由JSON字符串转换为JSON对象
or
var obj = JSON.parse(str); //由JSON字符串转换为JSON对象
Then, you can read it like this:
Alert(obj.name); Alert(obj.sex);
Special note:If obj is originally a JSON object, Then after using the eval() function to convert (even multiple conversions) it will still be a JSON object, but there will be problems after using the parseJSON() function to process it (throwing a syntax exception).
2. You can use toJSONString() or the global method JSON.stringify() to convert the JSON object into aJSON string.
For example:
var last=obj.toJSONString(); //将JSON对象转化为JSON字符
or
var last=JSON.stringify(obj); //将JSON对象转化为JSON字符
Then, you can read it like this:
alert(last);
Note:
Among the above methods, except for the eval() function that comes with js, the other methods all come from the json.js package. The new version of JSON has modified the API, injecting both JSON.stringify() and JSON.parse() methods into the built-in object ofJavascript, and the former becomes Object .toJSONString(), which becomes String.parseJSON(). If you are prompted that the toJSONString() and parseJSON() methods cannot be found, it means that your json package version is too low.
Recommended video tutorials: "JavaScript Tutorial"
The above is the entire content of this article, I hope it will be helpful to everyone's learning. For more exciting content, you can pay attention to the relevant tutorial columns of the PHP Chinese website! ! !
The above is the detailed content of How to convert json string to json object in js. For more information, please follow other related articles on the PHP Chinese website!