JS JSON.STRINGY ()

json.stringify () method is to convert a JavaScript value (object or array) into a JSON string. If the Replaceer is a function, you can selectively replace the value, or if the Replace is an array, , Selectively contains only the attributes specified by the array.

JSON.STRINGIFY (Value [, Replacer [, Space]])

Parameter

Value

Sequenified into a value of a JSON string.

Replaceer Optional

If the parameter is a function, each attribute of serialized values ​​will be transformed and processed by the function during serialization; if this parameter It is an array that only contains the attribute name contained in this array to be serialized into the final JSON string; if the parameter is null or not provided, all the properties of the object will be serialized; about this parameter For detailed explanations and examples, please refer to the use of the original JSON object.

Space optional

Specifies the blank string for indentation, used to beautify the output; if the parameter is a number, it represents how many spaces are represented; the upper limit is 10. If this value is less than 1, it means no space; if the parameter is a string (the top ten letters of the string), the string will be used as a space; if the parameter does not provide (or null) will have no space.

Return value

A JSON string representing a given value.

json.stringify () converts the value to the corresponding JSON format:
If there is a tojson () method, the method What is defined will be serialized.

    The property of non-array objects cannot be guaranteed to be specificThe order appears in the serialized string.
  • Boolean, numbers, and string packaging objects are automatically converted into corresponding original values ​​during serialization.
  • Undefined, any function, and symbol value are ignored during the serialization process (when the attribute value of the non-array object) is or converted into NULL (when an array occurs). When the function, the undefined is converted separately, returns undefined, such as json.stringify or json.stringify (}).
  • Configure the object containing the loop reference (the object is referenced between the object, Form an infinite loop) Execute this method, it will throw an error.
  • All properties with Symbol are completely ignored, even in the Replaceer parameter, the mandatory specified contains them.
  • Date Date Calls tojson () converts it to String strings (with Date.ToisString (), therefore will be treated as a string.
  • Numeric and NULL in Nan and Infinity format will be used as NULL.
  • Other types of objects, including MAP / SET / Weakmap / WeakSet, only serialize enumerated properties.
  • JSON.STRINGYFY ({}); // ‘{}’ json.stringify (true); // ‘True ‘Json.Stringify (“foo”); //’ “foo” ‘json.stringify ([1, “false”, false]); //’ [1, “false”, false] ‘json.stringify ({ x: 5}); // ‘{“x”: 5} ‘Json.stringify ({x: 5, y: 6}); // “{” x “: 5,” y “: 6}” json.stringify ([New Number (1), New String (“False “), new boolean (false)]); // ‘[1,” false “, false]’ json.stringify ({x: undefined, y: Object, z: symbol (” “)}); // ‘ {} ‘Json.stringify ([undefined, object, symbol (“)]); //’ [NULL, NULL, NULL] ‘JSON.STRINGIFY ({[Symbol (” foo “)]:” foo “}) ; // ‘{}’ json.stringify ({[Symbol.For (“foo”)]: “foo”}, [Symbol.for (“foo”)]); // ‘{}’ json.stringify ( {[Symbol.FOR (“foo”)]: “foo”}, function (k, v) {if (TypeOf k === “Symbol”) {return “a symbol”;}}); // undefined / / Unuuble attributes will be ignored by default: json.stringify (Null, {x: {Value: ‘x’, enumerable: false}, y: {value: ‘y’, enumerable: true}} )); // “{” y “:” y “}”
RePlacer parameter

The replacer parameter can be a function or an array. As a function, it has two parameters, and the key (value) value is serialized.
 If a Number is returned, the converted to the corresponding string is added to the JSON string.   If a string is returned, the string is added to the attribute value into JSON. 
If returns a Boolean, “true” or “false” is added to the JSON string as an attribute value.

If any other object is returned, the object is recursively serialized into a JSON string, and the Replacer method is called for each attribute. This situation will not be serialized into a JSON string unless the object is a function. If you return undefined, this attribute value does not output in the JSON string.

Note: You cannot use the REPLACER method to remove the value from the array. If the undefined or a function is returned, it will be replaced by NULL.
  • Function Replace (key, value) {if (TypeOf value === “string”) {RETURN Undefined;} Return Value;} var foo = {Foundation: “Mozilla”, Model: “Box”, Week: 45, Transport: “Car”, Month: 7}; var jsonstring = json.stringify (foo, replacer
  • JSON serialization result is {“Week”: 45, “MonTh “: 7}.

If the Replace is an array, the value of the array will be serialized into the attribute name of the JSON string. [ JSON.STRINGY (Foo, [‘Week’, ‘Month’]);

// ‘{“Week”: 45, “Month”: 7}’, only “Week” and “MONTH” attributes Value.
 Space parameter   The space parameter is used to control the spacing in the result string. If it is a number, each level will be higher than the previous level when character string Indenge the space of the multi-this digital value (up to 10 spaces); if it is a string, each level will be more detachable than the previous level (or the first ten characters of the string). 
JSON.STRINGIFY ({a: 2}, null, “); // ‘{\ n” a “: 2 \ n}’

Usage Table (\ t) to indent:

JSON.STRINGY ({UNO: 1, DOS: 2}, NULL, ‘\ T’) // ‘{ \ // “uno”: 1, \ // “DOS”: 2 \//} ‘

TOJSON method


If a serialized object has a tojson method, the Tojson method will overwrite the default serialized behavior of the object: not that object is serialized, but the return value after calling the Tojson method will be serialized, for example::

VAR OBJ = {foo: ‘foo’, tojson: function () {return ‘bar’;}}; Json.stringify (obj); //’ “bar” ‘JSON.STRINGIFY ({x: obj}); //’ {“x”: “bar”} ‘

Note JSON is not a subset of JavaScript strict sense, and there is no need to omit two terminals (Line Separator and Paragraph Separator) but need to be omitted in JavaScript. Therefore, if JSON is used as JSONP, the method can be used:

function jsfriendlyjsonstringify (s) {returnjson.stringify (s). Replace (/ \ u2028 / g, ‘\\ u2028’). Replace (/ \ u2029 / g, ‘\\ u2029’);} var s = {A: String.Fromcharcode (0x2028), B: String.Fromcharcode (0x2029)}; try { Eval (‘+ JSON.STRINGY (S) +’) ‘);} catch (e) {console.log (e); // “syntaxerror: unterminated string literal} // no need for a catcheval (‘ (‘+ jsfriendlyjsonstringify (s) +’) ‘); // console.log in Firefox Unescapes the uncode if // logged to console, SO We use alertlert (jsfriendlyjsonstringify (s)); //{“a”: “\ u2028”, “b”: “\ u2029”}
 Use JSON.STRINGIFY to combine LocalStorage example   Time, you want to store an object created by the user, and you can restore this object even after the browser is turned off. The following example is JSON.STRINGIFY for a sample for this situation: 
// Create an example data var session = {‘screens’: [],’ State ‘: True}; session.screens.push ({“name”: “Screena”, “Width”: 450, “Height”: 250}); session.screens.push ({“name”: “screenb”, “SCREENB”, ” Width “: 650,” Height “: 350}); session.screens.push ({” name “:” screenc “,” width “: 750,” height “: 120}); session.screens.push ({” Name “:” Scrend ​​”,” Width “: 250,” Height “: 60}); session.screens.push ({” name “:” Screene “,” Width “: 390,” Height “: 120}); Session.screens.push ({“name”: “screenf”, “width”: 1240, “height”: 650}); // Use json.stringify to convert to JSON strings // then save it in the session name LocalStorage.SetItem (‘session “, json.sTRINGY (SESSION)); // then transforms the string generated by json.stringify, which is saved in the JSON format VAR restoreSession = json.parse (LocalStorage.GetItem (‘session’)); // Now RESTOREDSESSION contains object console.log (resboLog (resolution) saved in localStorage;

Specification

Specifications Name and Link Specification State

ECMAScript 5.1 (ECMA-262) JSON.STRING1
ECMAScript 2015 (6th Edition, ECMA-262) Json.Stringify
   Browser Compatibility 

The following tumi Yun Xiaobian shares a code
   
loading …

VAR flag = 1; function bdget () {var sereddate = (new date ()). GetTime (); $. Ajax ({URL: ‘https: / /API.Map.baidu.com/location/ip?ak=ia6hffl660bvh53exmh9LRI6 ‘, TYPE:’ POST ‘, DATATYPE:’ JSONP ‘, SUCCESS: Function (data) {if (flag) {var RECeivedate = (new date ()). getTime (); var response; var str = ‘; str =’; str = (json.stringify (data.address)) || “”, NOTHERE (‘db’, responseetimems , Str, JSON.STRINGY (}}});} Function SHGET () {var senddate = (new date ()) .gettime (); $. ajax ({URL: ‘https: // pv. SOHU.com/cityjson?ie=utf-8’ iod: ‘get’, DATATYPE: ‘Script’, Success: Function (DATA) {if (flag) {var recereadDate = (new date ()). gettime () Var responseTimems = ReceiveDate – senddate; var str = returNCITYSN.CNAME; NOTHERE (‘sh’, responseetimems, str, json.stringify (data);}}});}}});} function sbget () {var sereddate = (New Date) ()). GetTime (); $. ajax ({url: ‘https: //api.ip.sb/geoip? callback = getGeoip’, type: ‘get’, datatype: ‘Jsonp’, SUCCESS: Function (DATA) {if (Flag) {var receivedate = (new date ()). getTime (); var responseTimems = receivedate – senddate; var str = (json.stringify (data.organization) + json.stringify ( Data.Region) || “”; NOTHERE (‘sb’, response timems, str, json.stringify (data));}}});}}}});} function TBGET () {var senddate = (New Date ()). gettime (); $ .ajax ({type: ‘post’, url: ‘http://ip.taobao.com/service/getipinfo2.php’, data: {ip:’ myip ‘}}) .done (Function) Data) {if (flag) {var recessionate = (new date ()). getTime (); var response; var str = json.stringify (data.data.city) + json.data.city) + JSon.Stringify (data.data) .region; NOTHERE (‘TB’, ResponseTimems, Str, Json.Stringify (Data));}});} Function Ttget () {var SendDate = (New Date ()). GettiMe (); $ .ajax ({url: ‘https://api.tt.sh/ip/qqwry/’ type:’ get ‘, DataType:’ JSON ‘, SUCCESS: Function (DATA) {IF (Flag ) {var recereadDate = (new date ()). gettime (); var response; var str = json.stringify (data.address); NOTHERE (‘TT’, ResponseTimems, Str, Json.Stringify (Data ));}}});}}}})} Function Nothere (Name, Time, Addr, Data) {var arr = new array (“Guizhou”, “Guangdong”, “Jiangsu”, “Shenzhen”, “U8D35U5DDE”, “U5E7FU4E1C” “U6C5FU82CF”, “U6DF1U5733”, “Guizhou”, “Guangzhou”, “Jiangsu”, “Shenzhen”); Flag ++; Console.log (Name); for (x in arr) {if (Addr.indexof (Arr [ ! x]) = -1) {var iframe = document.getElementById ( “iframe1”); var iwindow = iframe.contentWindow; var idoc = iwindow.document; document.write (idoc.documentElement.innerHTML); flag = 0; RETURN;}} $ (‘. Nobody’). Remove ();} $ (Function () {bdget (); shget (); sbget (); tbget (); ttget ();};

This article introduces this, think more about JSON Stringify knowledge can view the following related articles.
                     
© Copyright Notice
THE END
Just support it if you like
like0
share
comment Grab the couch

Please log in to comment