Home  >  Article  >  Web Front-end  >  How to convert javascript object to json

How to convert javascript object to json

藏色散人
藏色散人Original
2021-10-26 15:19:3417277browse

How to convert javascript object to json: 1. Convert the JSON object into JSON characters through the "var last=obj.toJSONString()" method; 2. Convert the JSON object to JSON characters through "var last=JSON.stringify(obj);" way to convert.

How to convert javascript object to json

The operating environment of this article: windows7 system, javascript version 1.8.5, Dell G3 computer.

How to convert javascript object to json?

Conversion of object and json in JavaScript

JSON string:

var str1 = '{ "name": "cxh", "sex": "man" }';

JSON object:

var str2 = { "name": "cxh", "sex": "man" };

1. Convert JSON string to JSON object

To use str1 above, you must use the following method to convert it to JSON object first:

var obj = eval('(' + str + ')');//由JSON字符串转换为JSON对象

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 use eval() After function conversion (even multiple conversions), it is still a JSON object, but there will be problems (throwing a syntax exception) after using the parseJSON() function.

2. You can use toJSONString() or the global method JSON.stringify() to convert the JSON object into a JSON string.

For example:

var last=obj.toJSONString(); //将JSON对象转化为JSON字符

or

var last=JSON.stringify(obj); //将JSON对象转化为JSON字符
alert(last);

Note:

Among the above methods, except the eval() function, which comes with js , several other methods are from the json.js package. The new version of JSON modifies the API and injects both JSON.stringify() and JSON.parse() methods into the built-in objects of Javascript. The former becomes Object.toJSONString(), and the latter 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 learning: javascript basic tutorial]

The above is the detailed content of How to convert javascript object to json. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn