1. Convert a JSON string to a JSON object

This can be parsed using JavaScript’s eval() function as follows:

    var json = '{"key":"value","jian":"zhi"}';
    var obj = eval("(" + json + ")");
 
    console.log(obj);         // Console returns Object
    console.log(obj.key);     // The console returns value
    console.log(obj.jian);    // Console returns to zhi
Copy the code

Or parse with the json.parse () method as follows:

var json = '{"key":"value","jian":"zhi"}';
var obj =JSON.parse(json);
 
console.log(obj);         // Console returns Object
console.log(obj.key);     // The console returns value
console.log(obj.jian);    // Console returns to zhi
Copy the code

Let’s look at the json.parse () method again:

var value = 1;
var jsonstr = '{"name":"jifeng","company":"taobao","value":++value}';
 
var json2 = JSON.parse(jsonstr);
console.log(json2);
console.log('value: '+ value);          
 Unexpected Token + in JSON at position
Copy the code

Json.parse () is the correct method to use. However, some browsers do not support this method. Go to github.com/douglascroc… Just download json2.js and add it to your HLML.

There is also a jsonstr.parsejson () method that converts json strings into JSON objects, which also requires support from the json2.js package.

2. Convert the JSON object to a JSON string

var json = '{"key":"value","jian":"zhi"}';
var obj =JSON.parse(json);
 
var str=JSON.stringify(obj);
console.log(str);        
// console returns {"key":"value","jian":"zhi"}
Copy the code

Parse (STR) corresponds to json.stringify (obj).

There is also a method called obj.tojsonString () that converts json objects toJSON strings, as opposed to jsonstr.parsejson ().

3. Convert the JSON character array to json array

This conversion is the same as string-to-object, except that you manipulate json arrays in a slightly different way than you manipulate JSON objects. Take a look at this code:

var arrayStr = '[{"name":"tom","age":"18"},{"name":"jake","age":"20"}]';
var arrayObj =JSON.parse(arrayStr);
 
console.log(arrayObj);         // Console Mandatory Array[2]
console.log(arrayObj[0]);      // Console returns Object
console.log(arrayObj[0].name); // The console returns Tom
console.log(arrayObj[1].age);  // Console returns 20
Copy the code

For JSON arrays, you can access them with subscripts. Since it is an array, it can also be iterated through the for loop.

4. Jquery parses the JSON string

Just a quick mention of jquery. When using jquery’s Ajax capabilities, there is a dataType property that you can either set to JSON or use the $.getjson () method to get the value returned by the server, which is a JSON object, so no conversion is required. Parse () {$.parsejson (string); $.parsejson (string); $.parsejson (string)