json is simple, but you may not know these details

Basic introduction

The full name of JSON is JavaScript Object Notation. It is not a programming language, but a data format that can be transmitted between the server and the client. It was originally a subset of JavaScript, but now it exists independently in various programming languages.

It has the following usage scenarios

  • When transmitting network data, such as parameters in http request
  • Some configuration files in the project, such as package JSON file
  • Non relational database (NoSQL) uses json as the storage format

grammar

Its files are in json is a suffix, but the code at the top level of the json file is strictly limited. You can only write the following three types, otherwise the code will be marked red directly~

1. Simple value
Number, String, single quotation mark not supported, Boolean, null

2. Object value
It consists of key and value. Key is a string type, and double quotation marks must be added. The value can be simple value, object value and array value

3. Array value
Simple value, object value, array value

Serialize stringify

The json format is often used to carry parameters in http requests, but we generally do not use json directly in the code, because it is inconvenient to operate attributes in json data. Most of the time, objects are used. If you convert objects into json format, you can use the stringify method.

The stringify method has three parameters

  • Parameter 1 (required), which is passed in an object to indicate which object to stringify
  • Parameter 2 (optional): pass in an array or function. The array includes the key value of the object, which means to serialize the data of the specified key value in the object. The passed in function means to operate on the specified key/value value
  • Parameter 3 (optional) is used to change the json data presentation format after serialization

We operate on the following objects

const user = {
  name: "alice",
  age: 20,
  friends: ["lisa", "macus", "windy"],
  info: {
    teacher: "kiki",
  },
};
Direct conversion

When only one parameter is passed in, the basic serialization operation is performed

const str1 = JSON.stringify(user);
console.log(str1);

key value specified by operation
const str2 = JSON.stringify(user, ["name", "friends"]);
const str3 = JSON.stringify(user, (key, value) => {
  if (key === "age") {
    return value + 1;
  }
  return value;
});
console.log(str2);
console.log(str3);

When the second parameter is passed in, an array is passed in, which means that only the data with key values of "name" and "friends" are serialized; Pass in the function, indicating that when the operation key value is "age", value+1

Change json presentation format
const str4 = JSON.stringify(user, null, 2);
const str5 = JSON.stringify(user, null, "*");
console.log(str4);
console.log(str5);

Pass in the third parameter. 2 means line feed and 2 spaces are left blank, * means line feed and the content of each line is preceded by a * sign

Tojason method

If there is a toJSON method in the original object, the stringify method calls the toJSON method directly. We add the toJSON method to the above object, and the execution results of all stringify methods will change.

const user = {
  name: "alice",
  age: 20,
  friends: ["lisa", "macus", "windy"],
  info: {
    teacher: "kiki",
  },
  toJSON(){
    return 'hello world'
  }
};

const str1 = JSON.stringify(user);
const str2 = JSON.stringify(user, ["name", "friends"]);
const str3 = JSON.stringify(user, (key, value) => {
  if (key === "age") {
    return value + 1;
  }
  return value;
});
const str4 = JSON.stringify(user, null, 2);
const str5 = JSON.stringify(user, null, "*");

console.log(str1);
console.log(str2);
console.log(str3);
console.log(str4);
console.log(str5);

The execution result of the stringify method becomes the return value of the toJSON method

Parse parse

The parameters returned by the interface request are generally json data. To use, we must first convert it into an object through the parse method.

The parse method can accept two parameters

  • Parameter 1 (required), json data, indicates which json data will be converted into an object
  • Parameter 2 (optional): pass in the function to operate on the specified key/value value
const str =
  '{"name":"alice","age":21,"friends":["lisa","macus","windy"],"info":{"teacher":"kiki"}}';
  
const obj1 = JSON.parse(str)
const obj2 = JSON.parse(str, (key, value)=>{
  if(key === 'age'){
    return value - 1
  }
  return value
})

console.log(obj1)
console.log(obj2)

Pass in the function to process the data when the key value is age. At this time, operate value - 1

Copy

There are several forms of copying. The copied memory addresses point to different memory addresses

Direct assignment

By means of the equal sign, one object can be assigned to another object.

const user = {
  name: "alice",
  info: {
    hobbies: "tennis",
  },
};
const person = user;
user.name = "lisa";

console.log("user", user);
console.log("person", person);

But they actually point to the same object. If the value of one object is manipulated, the other object will also change

The performance in memory is as follows

Shallow copy

The shallow copy will only traverse one layer. If the value value in the object is an object or array, the deeper layer will not be copied. Expand the operator or object Assign can make shallow copies.

const user = {
  name: "alice",
  info: {
    hobbies: "tennis",
  },
};
const consumer = { ...user };
user.name = "lisa";
user.info.hobbies = "swimming";

console.log("user", user);
console.log("consumer", consumer);

After the shallow copy, the user and consumer are no longer the same object, but their info still points to the same object. Modify the properties in one info and the other will change

The performance in memory is as follows

Deep copy

Deep copy means that the copied object is completely independent of the original object, and any attribute of the operation will not affect each other. Deep copy can be realized through stringify and parse methods.

const user = {
  name: "alice",
  info: {
    hobbies: "tennis",
  },
};

const human = JSON.parse(JSON.stringify(user));
user.name = "lisa";
user.info.hobbies = "swimming";

console.log("user", user);
console.log("human", human);

At this time, user and human do not point to the same object, and the info object in them is not the same object

The performance in memory is as follows

There are problems in implementing deep copy with stringify and parse

Although stringify and parse can implement deep copy, there are still some problems with this method. If there are [methods, undefined, Symbol] in the object, it will be removed directly

const user = {
  name: "alice",
  height: undefined,
  [Symbol("age")]: 20,
  info: {
    hobbies: "tennis",
  },
  study() {
    console.log("I love reading~");
  },
};
const people = JSON.parse(JSON.stringify(user));

console.log("user", user);
console.log("person", people);

Only the data that conforms to the json specification is left

Because of this problem, stringify and parse methods are generally not used. You can write your own methods for processing deep copy. As for the custom deep copy methods, they will be described in detail in the following articles.

The above is the relevant content of json. There are still many places for developers to master about js advanced. You can see other blog posts I wrote and keep updating~

Keywords: Javascript

Added by simn_stv on Fri, 21 Jan 2022 09:11:09 +0200