Method parsing of js to convert a json string to a json object

  • 2020-03-29 23:40:34
  • OfStack

Such as:

JSON string:
Var str1 = '{"name": "CXH ", "sex": "man"}';
JSON objects:
Var str2 = {"name": "CXH ", "sex": "man"};

Convert a JSON string into a JSON object

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

// converted from JSON string to JSON object

Var obj = eval('(' + STR + ')');


Var obj = STR. ParseJSON (); // converted from JSON string to JSON object


Var obj = JSON. Parse (STR); // converted from JSON string to JSON object

Then, you can read:

Alert (obj. Name);

Alert (obj. Sex);

Special note: if obj is a JSON object, it will still be a JSON object after being converted (even multiple times) with the eval () function, but it will have problems (throwing syntax exceptions) with the parseJSON () function.

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

Such as:

Var last = obj. ToJSONString (); // converts JSON objects to JSON characters


Var last = JSON. Stringify (obj); // converts JSON objects to JSON characters

Alert (last);


In the above methods, except that the eval() function is native to js, the other methods all come from the json.js package. The new version of JSON modifies the API to inject both json.stringify () and json.parse () methods into Javascript built-in objects, with the former becoming object.tojsonstring () and the latter becoming string.parsejson (). If the prompt fails to find the toJSONString() and parseJSON() methods, your json package version is too low.

PS: this site also provides several powerful json parsing, conversion and formatting tools for you to choose from. I believe that the following json format data processing will be helpful for you:

Online JSON code verification, verification, beautification, formatting tools:

Online XML/JSON inter-conversion:

Json code online formatting/beautification/compression/editing/conversion tools:

C language style /HTML/CSS/json code format beautification tool:

Related articles: