Because JSON is very simple, it quickly swept the web world and became the ECMA standard. Almost all programming languages have libraries that parse JSON, and in JavaScript we can use JSON directly, because JavaScript has built-in JSON parsing.
To turn any JavaScript object into JSONis to serialize the object into a JSON-formatted string so that it can be passed to other computers over the network.
If we receive a string in JSON format, we just need to deserialize it into a JavaScript object, and we can use it directly in JavaScript.
Serialization (JS object-->json)
Let's first serialize this object into a JSON-formatted string:
var xiaoming = { ' xiaoming ', +, true, 1.65, null, ' middle-school ': ' \ ' w3c\ ' Middle School ', skills: [' JavaScript ', ' Java ', ' Python ', ' Lisp ']}; json.stringify (xiaoming);
To output a good look, you can add parameters to the output by indentation:
null, ' );
Results:
{ "name": "Xiaoming", "age": +, true, "height": 1.65, NULL , " Middle-school ":" \ "w3c\" Middle School ", " skills ": [ " JavaScript ", " Java ", " Python " , "Lisp" ]}
The second parameter controls how the object's key value is filtered, and if we only want to output the specified property, we can pass in Array :
Json.stringify (xiaoming, [' Name ', ' skills '], ' );
Results:
{ "name": "Xiaoming", "skills": [ "JavaScript", "Java", "Python" , "Lisp" ]}
You can also pass in a function so that each key-value pair of an object is processed first by the function:
function CONVERT (key, value) { if (typeof value = = = ' String ') { return Value.touppercase (); } return " );
The above code capitalizes all attribute values:
{ "name": "Xiaoming", "age": +, true, "height": 1.65, NULL , " Middle-school ":" \ "w3c\" Middle School ", " skills ": [ " JAVASCRIPT ", " JAVA ", " PYTHON " , "LISP" ]}
If we also want to control exactly how to serialize xiaoming, you can xiaoming define a toJSON() method that directly returns the data that the JSON should serialize:
varXiaoming ={name:' Xiao Ming ', Age:14, Gender:true, Height:1.65, Grade:NULL, ' middle-school ': ' \ ' w3c\ ' Middle school ', skills: [' JavaScript ', ' Java ', ' Python ', ' Lisp '], ToJSON:function () { return{//only name and age are output, and the key is changed:' Name ': This. Name, ' age ': This. Age}; }}; Json.stringify (xiaoming); //' {' Name ': ' xiaoming ', ' age ': 'Deserialization
To get a string in JSON format, we use JSON.parse() it to turn it into a JavaScript object :
//
Truejson.parse (' 123.45 ');
123.45
JSON.parse()You can also receive a function that transforms the parsed property:
function (key, value) { // put number * 2: if (key = = = ' name ') { return val UE + ' classmate '; } return // Object {name: ' Xiao Ming classmate ', age:14}
Use in the Json--javascript