Transformation between json object and json string

1. Convert json string to json object

1.1 Using the JSON.parse() function

var jsonStr = '{"name":"tom","age":23,"email":"[email protected]"}';
var json = JSON.parse(jsonStr);
console.log(json);// Object {name: "tom", age: 23, email: "[email protected]"}

1.2 Using the eval() function

var jsonStr = '{"name":"tom","age":23,"email":"[email protected]"}';
var json = eval ("(" + jsonStr + ")");
console.log(json);// Object {name: "tom", age: 23, email: "[email protected]"}

1.3 jQuery.parseJSON()

var jsonStr = '{"name":"tom","age":23,"email":"[email protected]"}';
var json = jQuery.parseJSON(jsonStr);
console.log(json);// Object {name: "tom", age: 23, email: "[email protected]"}

2. Convert json object to json string

Use JSON.stringify()

var jsonStr = '{"name":"tom","age":23,"email":"[email protected]"}';
var jsonStr = JSON.stringify(json);
console.log(json);// Object {name: "tom", age: 23, email: "[email protected]"}

Leave a Reply