web123456

JSON details

JSON details

JSON is a very important data format. It is not a programming language, but a data format that can be transferred between servers and clients.

Article Directory

  • JSON details
    • 1. Basic JSON syntax
    • 2. JSON serialization
      • JSON serialization method
    • 3. Stringify method
      • replacer parameter
    • 4. parse method
    • 5. Use JSON to serialize deep copy

1. Basic JSON syntax

The top level of JSON supports three types of values:

  • Simple values: Number (Number), String (String, single quotes are not supported), Boolean (Boolean), null type;
  • Object value: consists of key and value. The key is a string type and must be added with double quotes. The value can be a simple value, object value, and array value;
  • Array value: The value of an array can be a simple value, an object value, and an array value;
{
  "name": "hhh",
  "age": 18,
  "friend": {
    "name": "sam"
  }
}

[
  234,
  "abc",
  {
    "name": "amy"
  }
]
  1. Values ​​of compound types can only be arrays or objects, not functions, regular expression objects, or date objects.
  2. There are only four values ​​for the original type: string, numeric value (must be expressed in decimal), boolean value, andnull(Not usedNaN, Infinity, -Infinityandundefined)。
  3. StringMust be expressed in double quotes, single quotes cannot be used.
  4. The key names of the object must be placed in double quotes.
  5. Comma cannot be added after the last member of an array or object.

2. JSON serialization

In some cases we want to convert complex types in JavaScript into strings in JSON format, so that they can be processed easily:

  • For example, we want to save an object to localStorage;
  • But if we store an object directly, the object will be converted into a string in the format [object Object], which is not the result we want;

JSON serialization method

In ES5, the JSON global object is referenced, and there are two commonly used methods of this object:

  • stringify method: convert JavaScript type into the corresponding JSON string;
  • parse method: parse JSON string and return to the corresponding JavaScript type;
const obj = {
  name: "why",
  age: 18,
  friend: {
    name: "kobe"
  },
  hobbies: ["123","456","789"]
}


//Convert to string to save
const objString = JSON.stringify(obj)
localStorage.setItem("info",objString)

//Get the string back to the object
const itemString = localStorage.getItem("info")
const info = JSON.parse(itemString)
console.log(info);

3. Stringify method

(value[, replacer [, space]])

  • value: Will be serialized into a JavaScript object or value of a JSON string.
  • replacer optionally, to handle the value to be serialized.
  • space optional, specifying the blank string for indentation, used to beautify the output.

Return value:A JSON format string representing the given value.

replacer parameter

The replacer parameter can be used in the following three situations:

  1. If it is null, undefined or other types, it will be ignored and will not be processed;
JSON.stringify({key: 'json'}, null, null) // '{"key":"json"}'
JSON.stringify({key: 'json'}, true) // '{"key":"json"}'Copy the code

​ 2. If it is an array, only the attribute names contained in this array will be finally serialized into the result string.
Only valid for the object's properties, invalid for arrays.

const obj = {
  json: 'JSON',
  parse: 'PARSE',
  stringify: 'STRINGIFY'
}
JSON.stringify(obj, ['parse', 'stringify'])
// '{"parse":"PARSE","stringify":"STRINGIFY"}'

​ 3. If it is a function, each attribute of the serialized value will be converted and processed by the function;

Process:

  • The function has two parameters, the attribute name (key) and the attribute value (value), which are all serialized;
  • When called for the first time, the key is an empty string, and the value is the entire object that needs to be serialized;
  • During the second processing, the first result will be passed over, and each subsequent processing will receive the result of the previous processing;
  • Later, each attribute name and attribute value will be processed in turn, and will be returned after completion.

The () method converts a JavaScript object or value to a JSON string:

  • If a replacer function is specified, the value can be optionally replaced;
  • If the specified replacer is an array, it can optionally only contain the properties specified by the array;
const obj = {
  name: "why",
  age: 18,
  friend: {
    name: "kobe"
  },
  hobbies: ["123","456","789"]
}


//1. Direct conversion
const jsonString1 = JSON.stringify(obj)
console.log(jsonString1);
//{"name":"why","age":18,"friend":{"name":"kobe"},"hobbies":["123","456","789"]}


//# The second parameter replacer
//2.1 The second parameter replacer is: pass in an array, set which ones need to be converted
const jsonString2 = JSON.stringify(obj,["name","friend"])
console.log(jsonString2);
//{"name":"why","friend":{"name":"kobe"}}


//2.2 The second parameter replacer is: pass in the callback function
const jsonString3 = JSON.stringify(obj,(key, value) => {
  if(key === "age") {
    return value + 1
  }
  return value
})
console.log(jsonString3);
//{"name":"why","age":19,"friend":{"name":"kobe"},"hobbies":["123","456","789"]}


//# The third parameter space
const jsonString4 = JSON.stringify(obj, null, "---")
//If the second parameter is not required, pass null
//(obj, null, 2), when the last parameter is 2 (number), the default is to distinguish it by spaces
console.log(jsonString4)
// {
// ---"name": "why",
// ---"age": 18,
// ---"friend": {
// ------"name": "kobe"
// ---},
// ---"hobbies": [
// ------"123",
// ------"456",
// ------"789"
// ---]
// }

4. parse method

(text[, reviver])

  • text: The string to be parsed.
    If a number is passed, it will be converted into a decimal digital output.
    If a boolean is passed, it will be output directly.
    If null is passed, null is output.
    Other types of values ​​are not supported, otherwise an error will be reported.
  • Reviver: Optional, converter, can be used to modify the original value generated by parsing.

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

The () method is used to parse JSON strings and construct JavaScript values ​​or objects described by strings.
An optional reviver function is provided to perform transformations (operations) on the resulting object before returning.

const JSONString = '{"name":"why","age":18,"friend":{"name":"kobe"},"hobbies":["123","456","789"]}'

const info = JSON.parse(JSONString,(key,value) => {
  if(value === "age") {
    return value - 1
  }
  return value
})
console.log(info);
// {
//   name: 'why',
//   age: 18,
//   friend: { name: 'kobe' },
//   hobbies: [ '123', '456', '789' ]
// }

5. Use JSON to serialize deep copy

The generated new object is not the same object as the previous object:
It is equivalent to a deep copy;

const obj = {
  name: 'why',
  age: 18,
  friend: {
    name: 'kobe'
  }
}

const objString = JSON.stringify(obj)
const info = JSON.parse(objString)

console.log(info);
//{ name: 'why', age: 18, friend: { name: 'kobe' } }

console.log(info === obj)//false
info.friend.name = "james"
console.log(obj.friend.name)//kobe

Note: This method is powerless to function
There is no foo function in the info created, because stringify does not process the function;

For example:

const obj = {
  name: 'why',
  age: 18,
  friend: {
    name: 'kobe'
  },
  eating() {
    console.log("eating~")
  }
}

const objString = JSON.stringify(obj)
const info = JSON.parse(objString)

console.log(info);
//{ name: 'why', age: 18, friend: { name: 'kobe' } }

console.log(info === obj)//false
info.friend.name = "james"
console.log(obj.friend.name)//kobe

Here we add methods in the obj object, but there is no function in the converted info object