Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

preface

Is the following obj a JSON object?

{
    name:"tom"[Symbol.for("sex")]: 1
}
Copy the code

Answer: No, object literals.

JSON and object literals

JSON

  1. Make sure the key is in double quotes (that is, strings)
  2. The value can only be: number, Boolean, array, NULL, object, string. Values also use double quotes if they are strings

Here are the objects

{
    "name": "tom"."age": 10
}
Copy the code

Object literals

The following are object literals, not JSON

{
    "name": "tom"."age": undefined // Can only be numbers, booleans, arrays, null, objects, strings
}

{
    name:"tom"[Symbol.for("sex")]: 1  // Keys can only be strings
}

{
   name:"tom"[Symbol.for("sex")]: 1.// Redundant
}
Copy the code

JSON.parse()

The parsed JSON string method constructs JavaScript values or objects described by the string.

JSON.parse(text[, reviver])

The second parameter reviver

Parse you’ve all used json.parse, but it has a second argument. How many of you care?

Reviver is a function with two arguments:

  • K: The property key is being converted
  • V: The value of the current attribute to be converted

If reviver returns undefined, the current attribute will be removed from the owning object. If other values are returned, the returned value will become the new attribute value of the current attribute.

Two other points to note:

Traversal sequence

This function is iterated in the following order: start at the innermost layer and work out in hierarchical order.

var jsonStr = '{"name": "toothpaste ", "count": 10, "orderDetail": {"createTime": 1632996519781, "orderId": 8632996519781, "more": {"desc": "Description"}}} '

JSON.parse(jsonStr, function(k, v){
    console.log("key:", k);
    return v;
})

// key: name
// key: count
// key: createTime
// key: orderId
// key: desc
// key: more
// key: orderDetail
// key: 
Copy the code

this

This is the object above which the current property key belongs.

var jsonStr = '{"name": "toothpaste ", "count": 10, "orderDetail": {"createTime": 1632996519781, "orderId": 8632996519781}}'

JSON.parse(jsonStr, function(k, v){
    console.log("key:", k,  ",this:".this);
    return v;
})

// key: name,this: {name: 'toothpaste ', count: 10, orderDetail: {... }}
// key: count,this: {name: 'toothpaste ', count: 10, orderDetail: {... }}
// key: createTime ,this: {createTime: 1632996519781, orderId: 8632996519781}
// key: orderId ,this: {createTime: 1632996519781, orderId: 8632996519781}
// key: orderDetail,this: {name: 'toothpaste ', count: 10, orderDetail: {... }}
// key:,this: {"": {... }}
Copy the code

JSON.stringify()

Method converts a JavaScript object or value to a JSON string.

grammar

JSON.stringify(value[, replacer [, space]])

It has a second parameter and a third parameter.

  • replaceroptional

If the parameter is a function, each attribute of the serialized value is converted and processed by the function during serialization; If the parameter is an array, only the property names contained in the array will be serialized into the final JSON string; If this parameter is null or not provided, all attributes of the object are serialized.

  • spaceoptional

Specifies a blank string for indentation, which is used to beautify the output (pretty-print). If the argument is a number, it represents how many Spaces there are; The upper limit is 10. If the value is less than 1, there are no Spaces. If the parameter is a string (the first 10 characters are taken when the string is longer than 10 characters), the string will be used as a space. If this parameter is not provided (or null), there will be no Spaces.

Replacer is useful for data transformation

Space is useful for beautifying formatted output

limit

  • Circular references will report an error,
  • The value of BigInt will also report an error

Other:

Json.stringify converts input to a string, so there are many restrictions. For example, undefined is ignored, Symbol’s key is ignored, NaN and Infinity values and null are treated as null. Date will become an ISO string and so on.

See more at developer.mozilla.org/zh-CN/docs/…

toJSON

If an object being serialized has a toJSON method, the toJSON method overrides the default serialization behavior of the object.

var prodcut = {
    "name": "Toothpaste"."count": 10."orderDetail": {
        "createTime": 1632996519781."orderId": 8632996519781
    },
    toJSON(){
        return {
           name: "Toothpaste"}}}JSON.stringify(prodcut) // '{"name":" toothpaste "}

Copy the code

summary

Did you harvest anything today?