The JSON format (JavaScript Object Notation) is a text format used for data interchange. It is easy to write. Serialize objects, arrays, values, strings, booleans, and NULL based on JavaScript native syntax.

In ES5, a JSON object was added specifically for handling JSON-formatted data. JSON is an object, but has only two methods: parse and stringify, no constructors, and no attributes.

typeof JSON= = ='object'
Copy the code

JSON.parse

Json.parse () is used to parse JSON strings to get the corresponding JavaScript values or objects.

JSON.parse('{}') / / {}
JSON.parse('true') // true
JSON.parse('null') // null
Copy the code

JSON. Parse the grammar

JSON.parse(text[, reviver])
Copy the code
  • Text: String to be parsed into. If a number is passed in, it is converted to a decimal number output. If a Boolean value is passed in, it is printed directly. If null is passed, null is printed. Values of other types are not supported; otherwise, an error is reported.
  • Reviver: Optional, converter that can be used to modify the original value generated by parsing.

Return value: JavaScript object/value corresponding to the given JSON text.

Reviver parameter

Reviver function, which transforms parsed JavaScript values and returns the final result.

Conversion process:

  • The parsed value itself and all attributes it may contain are respectively called reviver functions in a certain traversal order, with attribute name and value as two parameterskeyvalueThe incoming.

    Traversal order: By hierarchy, traversal from the inside out, finally reaching the top, is the parse value itself.
  • Reviver returns undefined, deletes the object, and if any other value is returned, it becomes the new value of the current property.
  • When you get to the top level, the key argument is an empty string because there are no attributes left' 'The value argument is the current resolved value.

For reviver function key and value, different data types:

  • Base value types data (String, Number, Boolean) and NULL, as well as null objects{}And an empty array[]:

    Key is an empty string and value is the parsed value.

    Because it’s already the top layer, there’s no other properties.
  • Object: The key and value exist, corresponding to the attribute name and value. The top layer returns a value with a null key.
  • Array: Key corresponds to array index, value corresponds to element value; The top layer returns a value with a null key.

Basic type conversions:

JSON.parse('5'.function (key, value) {
  console.log(`key:${key}, value:${value}`)})// key:, value:5
JSON.parse('null'.function (key, value) {
  console.log(`key:${key}, value:${value}`)})// key:, value:null
JSON.parse('{}'.function (key, value) {
  console.log(`key:${key}, value:`, value)
})
// key:, value:{}
Copy the code

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 ", "info" : {" age ": 25," sex ": 1}}'.function (key, value) {
  console.log(`key:${key}, value::`, value)
})
// key:user, value:
// key:age, value:: 25
// key:sex, value:: 1
// key:info, value:: {}
// key:, value:: {}
Copy the code

Data processing:

JSON.parse('[1, 2]'.function (key, value) {
  if(key === ' ') {
    return value
  }
  return value + 3
})
/ / [4, 5]
Copy the code

JSON parse characteristics

When parsing JSON strings, you need to be aware of the JSON format specifications. Otherwise, errors may occur. JSON data has strict rules on the type and format of values. The specific rules are as follows:

  1. This method uses the string type JSON format data. The method also supports numeric, Boolean, and NULL values, converting the corresponding literals. Other types are not supported.
JSON.parse('" China")
// 'China'
JSON.parse(null) // null
JSON.parse(111.) / / 111
JSON.parse(0x12) / / 18
JSON.parse(true) // true
JSON.parse([])
// Uncaught SyntaxError: Unexpected end of JSON input
Copy the code
  1. 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
Copy the code
  1. Only decimal strings are supported, but must be followed by a digit after the decimal point.
JSON.parse('111') / / 111
JSON.parse('0x12')
// Uncaught SyntaxError: Unexpected token x in JSON at position 1
JSON.parse('111.232') / / 111.232
JSON.parse('111.')
// Uncaught SyntaxError: Unexpected end of JSON input
Copy the code
  1. Cannot use undefined, Symbol, BigInt, or NaN, Infinity, or -infinity.
JSON.parse(undefined)
// Uncaught SyntaxError: Unexpected token u in JSON at position 0
JSON.parse(Symbol())
// Uncaught TypeError: Cannot convert a Symbol value to a string
JSON.parse('12n')
// Uncaught SyntaxError: Unexpected token n in JSON at position 2
Copy the code
  1. Compound type, which can only be:[]{}This is a literal.

    Object constructors cannot be used because they are treated as execution statements and are not supported.

    Objects and arrays cannot be used. Functions, RegExp objects, Date objects, Error objects, etc.
JSON.parse('[]')
/ / []
JSON.parse('Object()')
// Uncaught SyntaxError: Unexpected token O in JSON at position 0
Copy the code
  1. Object attribute names must be in double quotes.
JSON.parse('{"key": 1 }')
// {key: 1}
JSON.parse('{key: 1 }')
// Uncaught SyntaxError: Unexpected token k in JSON at position 1
Copy the code
  1. The last member of an array or object cannot be followed by a comma.
JSON.parse([1, 2, 3, 4,])
// VM2771:1 Uncaught SyntaxError: Unexpected token ] in JSON at position 13
JSON.parse('{"key" : 1, }')
// VM2779:1 Uncaught SyntaxError: Unexpected token } in JSON at position 12
Copy the code
  1. Unicode escape is supported.
JSON.parse('{"\u0066":333}')
// {f: 333}
Copy the code
  1. Some control characters and escape characters are not supported, such as ‘\n’ and ‘\t’.
JSON.parse('"\n"')
// Uncaught SyntaxError: Unexpected token 
Copy the code

Other ways of parsing

There are other ways to turn a JSON string into a JSON object (a JS object value), but non-secure code.

  const str = '{"name":"json","age":18}'
  const json = JSON.parse(str)
  const json = eval("(" + str + ")")
  const json = (new Function("return " + str))()
Copy the code

JSON.stringify

Json.stringify () converts a JavaScript object or value to a JSON-formatted string.

JSON. Stringify syntax

JSON.stringify(value[, replacer [, space]])
Copy the code
  • Value: The JavaScript object or value to serialize into a JSON string.
  • Replacer is optional and is used to process values to be serialized.
  • Space is optional, specifying a blank string for indentation to beautify the output.

Return value: A JSON-formatted string representing the given value.

Replacer parameter

The replacer parameter can work in one of three ways:

  1. If the value is null, undefined, or any other type, it is ignored and no action is taken.
JSON.stringify({key: 'json'}, null.null) // '{"key":"json"}'
JSON.stringify({key: 'json'}, true) // '{"key":"json"}'
Copy the code
  1. If it is an array, only the property names contained in the array will eventually be serialized into the result string. This applies only to properties of objects, not arrays.
const obj = {
  json: 'JSON'.parse: 'PARSE'.stringify: 'STRINGIFY'
}
JSON.stringify(obj, ['parse'.'stringify'])
// '{"parse":"PARSE","stringify":"STRINGIFY"}'
Copy the code
  1. If it is a function, each attribute of the serialized value is converted and processed by the function;

Processing process:

  • The function takes two arguments, the property name (key) and the property value (value).
  • On the first call, key is an empty string and value is the entire object to serialize;
  • The second processing will pass the results of the first processing, and each subsequent processing will receive the results of the last processing;
  • Later, each attribute name and value is processed in turn and returned when complete.
JSON.stringify({ json: 1.stringify: { val: 'rr'}},(key, value) = > {
  console.log(` key:${key}, the value: `, value)
  return value
}) 
// key:, value: {json: 1, stringify: {... }}
// key: json, value: 1
// key: stringify, value: {val: 'rr'}
// key: val, value: rr
// '{"json":1,"stringify":{"val":"rr"}}'
Copy the code

Value type handling:

  • If it returns a primitive string, number, Boolean, or NULL, it is added directly to the serialized JSON string.
  • If another object is returned, the properties of that object are serialized in sequence. If it is a function, no processing is done.
  • If returned or undefined, the property is not printed.
  • 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"}'
Copy the code

The following example returns the value of an object:

JSON.stringify({ json: 1.stringify: 'rr' }, (key, value) = > {
  if (typeof value === 'object') { // The first time the whole object is returned, the type is object
    return { parse: 'dd'}}return value
}) 
'{"parse":"dd"}'
Copy the code

Space parameters

The space argument is used to control the spacing within the resulting string and beautify the output. There are three types of values that can be entered:

  • In the case of numbers, each level is indented more Spaces than the previous level, ranging from 1 to 10, that is, at least 1 and at most 10 Spaces.
  • If it is a string, the string is appended to each line of serialization, and the string is indented at most one character at each level.
  • If the value is null, undefined, or any other type, it is ignored and no action is taken.
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"}'
Copy the code

JSON. Stringify characteristics

  1. Primitive String, Number, and Boolean values, as well as String, Boolean, and Number object values, are printed as primitive strings.
JSON.stringify(333) / / '333'
JSON.stringify(true) // 'true'
JSON.stringify(new String('333')) / / '" 333"
JSON.stringify(Boolean(true)) // 'true'
Copy the code
  1. A string of basic type. The conversion result will be quoted.

Because when restored, double quotes let JavaScript know it’s a string, not a variable.

JSON.stringify('json') = = ='json' // false
JSON.stringify('json') = = ='"json"' // true
Copy the code
  1. Undefined, function, symbol, and XML objects:
  • When present in an Object, it is ignored;
  • When it appears in an array, it is serialized to NULL;
  • When present alone, undefined is returned.
JSON.stringify(Symbol()) // undefined
JSON.stringify([Symbol(), Math.abs, undefined]) // '[null,null,null]'
JSON.stringify({ [Symbol()] :Math.abs, key: undefined }) / / '{}'
Copy the code
  1. NaN, Infinity, and -infinity values, as well as null, are all serialized to NULL.
JSON.stringify(null) // 'null'
JSON.stringify(NaN) // 'null'
Copy the code
  1. Object, andMap/Set/WeakMap/WeakSetWhen serialized, the object’s non-traversal property is ignored.
const obj = {}
Object.defineProperties(obj, {
  'json': { value: 'JSON'.enumerable: true },
  'stringify': { value: 'STRINGIFY'.enumerable: false}})JSON.stringify(obj)
// '{"json":"JSON"}'
Copy the code
  1. Properties whose attribute name is symbol are ignored.
JSON.stringify({[Symbol()] :333}) / / '{}'
Copy the code
  1. The properties of objects other than arrays can be out of order when serialized.
const a = { '1': 911.'r': 822.'11': 9922}
JSON.stringify(a)
// '{"1":911,"11":9922,"r":822}'
Copy the code
  1. The converted object if definedtoJSON()Method, the return value of which is the serialized result of the transform object.

    The procedure ignores other attributes.
const a = { key: 'json' }
a.toJSON = () = > 'JSON'
JSON.stringify(a)
// '"JSON"'
Copy the code
  1. Both RegExp objects and Error objects are serialized as empty object strings.
JSON.stringify(/\d/) / / "{}"
JSON.stringify(new Error())  / / "{}"
Copy the code

To serialize the object, you need to set up the toJSON method.

RegExp.prototype.toJSON = RegExp.prototype.toString
JSON.stringify(/\d/) // '"/\\\\d/"'
Copy the code
  1. The Date object already defines toJSON() and converts it to a string, so it can be serialized.

    Date.toISOString().
JSON.stringify(new Date())
/ / '" 2021-12-31 T02:24:05. 477 z "'
Copy the code
  1. An error is thrown when an object referenced by the loop executes this method. Objects refer to each other in an infinite loop.
const a = {}
a.key = a
JSON.stringify(a)
// Uncaught TypeError: Converting circular structure to JSON
Copy the code
  1. Converting a value of type BigInt raises TypeError. The BigInt value cannot be JSON serialized
JSON.stringify(12n)
// Uncaught TypeError: Do not know how to serialize a BigInt
Copy the code
  1. Better support for Unicode escape characters
const a = {'\u0066': 333}
JSON.stringify(a)
// '{"f":333}'
Copy the code