Json.stringify ()/Json.parse ()

Source: Internet
Author: User

Json.stringify () This method converts the JavaScript object to a JSON string.

Json.parse () This method converts a JSON string to a JavaScript object.

"Here's a look at the detailed answers to these two methods."

There are no variables and trailing semicolons in the JSON data, and the data must be enclosed in double quotes, and single quotes will report syntax errors.

Data format for JSON:

{        "name": "Chef",        "child":{            "name1": "Children",            "Age1": [                "One",                                "One", "three"            ],            "Hello": "World"         },        "age":    

Json.stringify ()

Serializes a JavaScript object into a JSON string ignoring indents and spaces, and you can change the single quotation mark to double quotation marks, and this method can also pass in the second argument, which can be an array or a function. If it is an array, then the elements of the array must match the keys in the JavaScript object (key-value pairs)

If it is an array, then the key value pair of the JavaScript object that serializes this array element corresponds

//This object runs through the full textvarJS = {        "Name": "Chef",        "Child":{            "Name1": "Children",            "Age1":[                "One",                "Both",                "Three"            ],            "Hello": "World"        },        "Age": 33    }    //serializes a JavaScript object into a JSON string ignoring indents and spaces    varJs_json =json.stringify (JS); Console.log (Js_json); //{"name": "Chef", "child": {"name": "Children", "Age": ["One", "one", "three"], "Hello": "World"}, "Age" :    //serialization options Incoming array    varJs_option = json.stringify (js,["Child", "age"]); //only the specified key has been serialized: child of AgeConsole.log (js_option);//{"Child": {' age ': ["One", "one", "three"]}, "Age" :

You can also pass in a function that has two parameters, the key-value pair (key,value) of the JSON string being serialized, which can be changed inside the function.

//serialization option to pass in a function    varJS_FN = json.stringify (js,function(key,value) {Switch(key) { Case"Age1":                //separate the values of age1 into strings with commas                returnValue.join (",");  Case"Name1":                //Replace the original value                return"Changed the original value directly.";  Case"Hello":                //Delete the key value pair                returnundefined; //without the default, the sentence gets no data .            default:                returnvalue;    }    }); Console.log ("Result of incoming function:" +JS_FN); //result of incoming function: {"name": "Chef", "child": {"name1": "changed the original value directly", "Age1": "One,two,three"}, "Age" :

  

You can also pass in the third parameter, (the second argument does not pass can write null) the third parameter is to control the JSON string indentation, it is a number or string, the number is indented at most 10, if the incoming greater than 10 is automatically converted to 10, if the string is passed, use this string as an indent instead of a space

// Pass in    the third parameter to control the indentation of the string var js_indent = json.stringify (js,null, 4);    Console.log ("indented JSON string:" +js_indent);     /*     Browser Execution effect:         indented JSON string: {            "name": "Chef",            "child": {                "name1": "Children",                "Age1" : [                    "One", "one", "                    three"                ],                "Hello": "World"            },    "age": */


ToJSON ()

Defined in a JavaScript object, when serializing a JavaScript object, the Tojson method is called first and then the value returned by the Tojson is serialized, if the Tojson method returns undefined, Then the value of this JavaScript object is undefined, if the object containing the Tojson method is embedded in other objects, then the value of the object containing the Tojson method becomes null

varJs_tojson ={name:' Chef ', Age:' 22 ',        //define the ToJSON method in JavaScript objects like thisToJSON:function(){            return{Name: This. Name,age: This. Age};    }    }; //Call the Stringify () method to serialize the object    varTojsontext =json.stringify (Js_tojson); Console.log ("The result of calling ToJSON:" +tojsontext)//result of calling ToJSON: {"name": "Chef", "Age": "$"}

The order of serialization is to first check if there is a Tojson method in the JavaScript object, and if there is one then execute the Tojson method, return what to serialize.

The order of execution of the stringify () parameter:
1, the first parameter
2, check Tojson and execute
3, the second parameter
4, a third parameter

Json.parse ()

Parsing a JSON string into native JavaScript values if passed to parse () is not a valid JSON string, this method throws an error

// parse JSON string into native JavaScript value    var json_js = json.parse (js_json);     // Object {name: "Chef", Child:object, age:33}

The parse () method also has a second argument that can pass a function to it, which also has two values, and (Key,value) functions like the function of a second function of stringify ()

    //= = = Perse () the second parameter    varPERSE_FN ={name:"Chef", Age:66, Newdate:NewDate ()}//convert the Perse_fn object to a JSON string first    varPerse_json =json.stringify (PERSE_FN); //then convert the JSON string to a JavaScript object    varPerse_js = Json.parse (Perse_json,function(key,value) {Switch(key) { Case"Name":                //can change value                returnValue+ "Chef's Notes";  Case"Newdate":                //return Time Object                return NewDate (); //This default must have, or else it will be undefined,            default:                returnvalue;    }    }); Console.log (PERSE_JS);//Object {name: "Chef Chefs ' Notes", age:66, Newdate:thu 22:52:20 gmt+0800 (China Standard Time)}

The above is my summary of JSON.

Json.stringify ()/Json.parse ()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.