In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-03 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "how to use JSON.parse and JSON.stringify". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor learn how to use JSON.parse and JSON.stringify.
JSON format, (abbreviated JavaScript Object Notation), is a text format for data exchange and is easy to write.
Based on JavaScript native syntax, you can serialize objects, arrays, numeric values, strings, Boolean values, and null.
In ES5, a JSON object has been added to deal with data in JSON format.
JSON is an object, but there are only two methods: parse and stringify, which cannot be used as constructors and have no properties.
Typeof JSON = 'object'JSON.parse
JSON.parse () is used to parse the JSON string to get the corresponding JavaScript value or object.
JSON.parse ('{}') / / {} JSON.parse ('true') / / trueJSON.parse (' null') / / nullJSON.parse syntax JSON.parse (text [, reviver])
Text: the string to be parsed into.
If a number is passed in, it is converted to a decimal digital output.
If a Boolean value is passed in, it is output directly.
If null is passed in, null is output.
Other types of values are not supported, otherwise an error is reported.
Reviver: optional, converter, which can be used to modify the original values generated by parsing.
Return value: JavaScript object / value, corresponding to the object / value of the given JSON text.
Reviver parameter
The reviver function, which is used to transform the JavaScript value parsed by processing, and returns the final result after processing.
Conversion process:
The parsed value itself and all the attributes it may contain call the reviver function in a certain traversal order, and the attribute name and value are passed as parameters, key and value.
Traversal order: according to the hierarchy, traversing from the inside to the outside, and finally reaching the top level, is the parsed value itself.
If reviver returns undefined, the object is deleted, and if another value is returned, the value becomes the new value of the current property.
When traversing to the top level, because there are no attributes, the parameter key is an empty string''and the parameter value is the current parsed value.
For the two parameters of the reviver function, key and value, different data types:
Basic value type data (string, number, boolean) and null, as well as empty object {} and empty array []:
Then key is an empty string and value is the corresponding parsed value.
Because it is already at the top level, there are no other attributes.
Object object:
Then both key and value exist, corresponding to the property name and value respectively.
The top level returns a value with an empty parameter key.
Array:
Key corresponds to the array index and value corresponds to the element value.
The top level returns a value with an empty parameter key.
Conversion of basic types:
JSON.parse ('5years, function (key, value) {console.log (`key:$ {key}, value:$ {value} `)}) / key:, value:5JSON.parse (' null', function (key, value) {console.log (`key:$ {key}, value:$ {value}`)}) / key:, value:nullJSON.parse ('{}', function (key, value) {console.log (`key:$ {key}, value: `, value)}) / key: Value: {}
Object objects and arrays:
JSON.parse ('[1,2]', function (key, value) {console.log (`key:$ {key}, value: `, value)}) / / key:0, value: 1 / key:1, value: 2 / key:, value: (2) [empty × 2] JSON.parse ('{"user": "Zhang San", "info": {"age": 25, "sex": 1}', function (key) Value) {console.log (`key:$ {key}, value:: `, value)}) / / key:user, value:: Zhang San / / key:age, value:: 25max / key:sex, value:: 1max / key:info, value:: {} / / key:, value:: {}
Data processing:
JSON.parse ('[1,2]', function (key, value) {if (key =') {return value} return value + 3}) / / [4,5] JSON.parse feature
When parsing JSON strings, you need to pay attention to some specifications of JSON format, otherwise it will be easy to report errors.
JSON data has strict rules on the type and format of values. The specific rules are as follows:
This method uses string type JSON formatted data.
This method also supports three types of values, namely, numeric, Boolean, and null, and converts them into corresponding literal values.
Other types are not supported.
JSON.parse ('China') / / 'China' JSON.parse (null) / / nullJSON.parse (111.11.) / / 111JSON.parse (0x12) / / 18JSON.parse (true) / / trueJSON.parse ([]) / / Uncaught SyntaxError: Unexpected end of JSON input
Strings must use double quotation marks, not single quotation marks.
JSON.parse ('"String"') / / 'String'JSON.parse ('\ 'String\') / / Uncaught SyntaxError: Unexpected token'in JSON at position 0
Only decimal strings are supported, but numbers must be followed after the decimal point.
JSON.parse ('111') / / 111JSON.parse (' 0x12') / / Uncaught SyntaxError: Unexpected token x in JSON at position 1JSON.parse ('111.232') / / 111.232JSON.parse (' 111.') / / Uncaught SyntaxError: Unexpected end of JSON input
Undefined, Symbol, and BigInt cannot be used, and numbers do not support NaN, Infinity, and-Infinity.
JSON.parse (undefined) / / Uncaught SyntaxError: Unexpected token u in JSON at position 0JSON.parse (Symbol ()) / / Uncaught TypeError: Cannot convert a Symbol value to a stringJSON.parse ('12n') / / Uncaught SyntaxError: Unexpected token n in JSON at position 2
Compound types can only be literals such as: [] and {}.
The object constructor cannot be used because it is treated as an execution statement and is not supported.
You cannot use Object and Array, nor can it be functions, RegExp objects, Date objects, Error objects, and so on.
JSON.parse ('[]') / / [] JSON.parse ('Object ()') / / Uncaught SyntaxError: Unexpected token O in JSON at position 0
The property name of an object must be in double quotation marks.
JSON.parse ('{"key": 1}') / {key: 1} JSON.parse ('{key: 1}') / / Uncaught SyntaxError: Unexpected token k in JSON at position 1
After the last member of an array or object, you cannot add a comma.
JSON.parse ('[1,2,3,4,]) / / VM2771:1 Uncaught SyntaxError: Unexpected token] in JSON at position 13JSON.parse ('{"key": 1,}') / / VM2779:1 Uncaught SyntaxError: Unexpected token} in JSON at position 12
Support for unicode escape.
JSON.parse ('{"\ u0066": 333}') / / {f: 333}
Some control characters and escape characters are not supported, such as'\ n','\ t' and so on.
JSON.parse ('"\ n") / / Uncaught SyntaxError: other methods of Unexpected token parsing
There are other ways to convert a json string to a json object (js object value), but not safe code.
Const str ='{"name": "json", "age": 18} 'const json = JSON.parse (str) const json = eval ("(" + str + ")") const json = (new Function ("return" + str)) () JSON.stringify
JSON.stringify () converts a JavaScript object or value to an JSON format string.
JSON.stringify syntax JSON.stringify (value [, replacer [, space]])
Value: a JavaScript object or value that will be serialized into a JSON string.
Replacer is optional to handle the value to be serialized.
Space is optional, specifying a blank string for indentation to beautify the output.
Return value: an JSON format string that represents a given value.
Replacer parameter
The replacer parameter can be used in the following three cases:
If it is null, undefined or other type, it is ignored and no processing is done.
JSON.stringify ({key: 'json'}, null, null) / /' {"key": "json"} 'JSON.stringify ({key:' json'}, true) / /'{"key": "json"}'
If it is an array, only the attribute names contained in the array will eventually be serialized into the result string
Valid only for the properties of the object, not for arrays.
Const obj = {json: 'JSON', parse:' PARSE', stringify: 'STRINGIFY'} JSON.stringify (obj, [' parse', 'stringify']) / /' {"parse": "PARSE", "stringify": "STRINGIFY"}'
If it is a function, each property of the serialized value will be converted and processed by the function
Process:
The function takes two parameters, the attribute name (key) and the attribute value (value), which are serialized
On the first call, key is an empty string and value is the entire object that needs to be serialized
In the second processing, the result of the first time will be sent, and each subsequent processing will receive the result of the last processing.
Later, each property name and attribute value will be processed in turn, and will be returned when finished.
JSON.stringify ({json: 1, stringify: {val: 'rr'}}, (key, value) = > {console.log (`key:$ {key}, value: `, value) return value}) / / key:,value: {json: 1, stringify: {… }} / / key:json,value: 1rr / key:stringify,value: {val: 'rr'} / / key:val,value: rr//' {"json": 1, "stringify": {"val": "rr"}}'
Type handling of value:
If the primitive type string, number, Boolean value, null is returned, it is added directly to the serialized JSON string
If another object is returned, the properties of the object will be serialized later, and if it is a function, it will not be processed.
If either or undefined is returned, the property is not output.
When serializing an array, if value returns undefined or a function, it will be replaced by null.
JSON.stringify ({json: 1, stringify: 'rr'}, (key, value) = > {if (typeof value =' number') {return 'ss'} return value}) / /' {"json": "ss", "stringify": "rr"} 'JSON.stringify ({json: 1, stringify:' rr'}, (key Value) = > {if (typeof value = = 'number') {value = undefined} return value}) / /' {"stringify": "rr"}'
The following example is the processing when an object value is returned:
JSON.stringify ({json: 1, stringify: 'rr'}, (key, value) = > {if (typeof value =' object') {/ / when the entire object is returned for the first time, the type is object return {parse: 'dd'}} return value})' {"parse": "dd"} 'space parameter
The space parameter is used to control the spacing in the resulting string and beautify the output. There are three cases in which you can enter values:
If it is a number, when serializing, each level indents more spaces of the corresponding numeric value than the previous level, in the range of 1-10, that is, a minimum of 1 and a maximum of 10 spaces
If it is a string, when serialized, the string is added in front of each line, and each level indents the string more than the previous level, up to a character, and intercepts the string if it exceeds
If it is null, undefined, or other type, it is ignored and no processing is done.
JSON.stringify ({key: 'json'}, null, 2) / / {\ n "key": "json"\ n}' JSON.stringify ({key: 'json', list: {str:' str'}}, null,'| -') / /'{\ n |-"key": "json",\ n |-"list": {\ n |-str: "str"\ n | -}\ n} 'JSON.stringify ({key:' json'}) Null, null) / /'{"key": "json"} 'JSON.stringify feature
Basic type value strings, numbers, Boolean values, and String, Boolean, Number object values are all converted to the original value string output.
JSON.stringify (333) / / '333'JSON.stringify (true) / /' true'JSON.stringify (new String ('333')) / / '333' JSON.stringify (Boolean (true)) / / 'true'
For the basic type of string, the conversion result will be in double quotation marks.
Because when you restore, double quotes let JavaScript know that it is a string, not a variable.
JSON.stringify ('json') =' json' / / falseJSON.stringify ('json') =' json'/ / true
Undefined, function, symbol, and XML objects:
When it appears in the Object object, it is ignored
When it appears in an array, it is serialized into null
When it appears alone, undefined is returned.
JSON.stringify (Symbol ()) / / undefinedJSON.stringify ([Symbol (), Math.abs, undefined]) / /'[null,null,null] 'JSON.stringify ({[Symbol ()]: Math.abs, key: undefined}) / /' {}'
NaN, Infinity, and-Infinity equivalents, as well as null, are serialized to null.
JSON.stringify (null) / / 'null'JSON.stringify (NaN) / /' null'
Object objects, as well as objects of compound types such as Map/Set/WeakMap/WeakSet, ignore their non-traverable properties when serialized.
Const obj = {} Object.defineProperties (obj, {'json': {value:' JSON', enumerable: true}, 'stringify': {value:' STRINGIFY', enumerable: false}}) JSON.stringify (obj) / /'{"json": "JSON"}'
Properties with the name symbol will be ignored.
JSON.stringify ({[Symbol ()]: 333}) / /'{}'
In addition to arrays, the properties of other objects may be out of order when serialized.
Const a = {"1": 911, "r": 822,'11: 9922} JSON.stringify (a) / /'{"1": 911, "11": 9922, "r": 822}'
If the transformed object defines a toJSON () method, the return value of that method is the serialized result of the transformed object.
The process ignores other attributes.
Const a = {key: 'json'} a.toJSON = () = >' JSON'JSON.stringify (a) / /'"JSON"'
Both RegExp objects and Error objects are serialized into empty object strings.
JSON.stringify (/\ d /) / / "{}" JSON.stringify (new Error ()) / / "{}"
To serialize the corresponding object, you need to set the implementation of the toJSON method.
RegExp.prototype.toJSON = RegExp.prototype.toStringJSON.stringify (/\ d /) / /'"/\ d /"'
The Date object has defined toJSON () and converted it to a string string, so it can be serialized.
Same as Date.toISOString ().
JSON.stringify (new Date ()) / / "2021-12-31T02:24:05.477Z"
When this method is executed by an object referenced by a loop, an error is thrown.
Objects refer to each other to form an infinite loop.
Const a = {} a.key = aJSON.stringify (a) / / Uncaught TypeError: Converting circular structure to JSON
Converting values of type BigInt throws a TypeError error.
BigInt values cannot be serialized by JSON
JSON.stringify (12n) / / Uncaught TypeError: Do not know how to serialize a BigInt
Better support for unicode escape characters
Const a = {'u0066mm: 333} JSON.stringify (a) / / {"f": 333}' so far, I believe you have a better understanding of "how to use JSON.parse and JSON.stringify". You might as well do it in practice! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.