How to convert between string and json using js

1. Convert string type to Json object method

 1. Conversion methods supported by Javascript: eval

         eval(‘(‘ jsonstr ‘)’);

Note: You need to wrap a pair of parentheses around the json character. ie8 (compatibility mode), ie7 and ie6 can also use eval() to convert strings to JSON objects, but these methods are not recommended; the disadvantage is that it is not safe, eval will execute Expression in json string.

2. Conversion methods supported by browsers (Firefox, chrome, opera, safari, ie9, ie8) and other browsers:

JSON .parse(jsonstr); //Can convert json string to json object

On the contrary, the browser also provides a method to convert the Json object to the string type:

JSON.stringify(jsonstr);//Can convert json object into json pair string

3. Conversion methods supported by the jQuery plugin :

$.parseJSON( jsonstr ); //jQuery.parseJSON(jsonstr), can convert json string into json object

4. The official JSON conversion method :

http://www.json.org/ provides a json.js so that ie8 (compatibility mode), ie7 and ie6 can support JSON objects and their stringify() and parse() methods;

This js can be obtained at https://ift.tt/896Yn5v, generally json2.js is now used.

2. Convert Json object to String string method

The conversion methods supported by the browsers mentioned above are JSON.stringify(str):

JSON.stringify(jsonstr);//Can convert json object into json pair string

The post Method for converting between string and json using js first appeared on Lenix Blog .

This article is reprinted from https://blog.p2hp.com/archives/9182
This site is for inclusion only, and the copyright belongs to the original author.

Leave a Comment

Your email address will not be published.