“This article has participated in the good article call order activity, click to see: back end, big front end double track submission, 20,000 yuan prize pool for you to challenge!”

preface

In the process of front-end development, there are many scenarios for JSON processing, which is also a common requirement. JSON is a format for storing and transferring data. JSON is usually used to transfer data from a server to a web page, and it is a lightweight data exchange format. Especially when it comes to JS development, converting JSON data into JavaScript objects is a very common approach. This article shares a summary of the common JSON handling methods json.stringify () and json.parse () used by the front end.

Function is introduced

1, the JSON. Stringify ()

The json.stringify () method is used to convert a JavaScript object to a JSON string, that is, to parse a string from an object.

2, JSON. The parse ()

The json.parse () method is used to convert data into a JavaScript object, which is parsed from a string.

Simply put, the effects of json.stringify () and json.parse () are relative and mutually exclusive. For example, if you use json.stringify () to change object A to string B, you can use json.parse () to restore string B to object A directly.

Syntax and Parameters

1, the JSON. Stringify ()

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

Parameters:

  • Value: a mandatory parameter, the JavaScript value (typically an object or array) that you want to transform.
  • Replacer: An optional argument to the function or array used to convert the result. 
space: Optional to add indent, Spaces, and newlines to the text. Space can also be used with non-numbers, such as: \t.

Return value: Returns a string containing JSON text.

2, JSON. The parse ()

Syntax: json.parse (text[, reviver])

Parameters:

  • Text: A mandatory parameter, a standard valid JSON string that you want to convert.
  • Reviver: Optional argument, a function that converts the result, which will be called for each member of the object.

Return value: Returns a JavaScript object.

The instance

1. Use of json.stringify ()

Object turn string
var str = {"name":"sanzhanggui", "age":"30","gender":"male","phone":"15290331111"}; basic_str = JSON.stringify(str); console.log(basic_str); // Output a stringCopy the code

2. Use of json.parse ()

String to array
var jdList = []; var str1 = '[{\"createBy\":70446,\"createDate\":1622092153440,\"updateBy\":70446,\"updateDate\":1622092153440,\"remarks\":null,\"id \":4037,\"templateId\":61,\"fieldId\":132,\"fieldName\":\"JD\",\"fieldType\":\"1\",\"fieldLength\":999,\"fieldSetup\":nu ll,\"isRequired\":\"1\",\"isVisible\":\"1\",\"isFixed\":\"1\",\"reason\":null,\"lineAccounted\":null,\"value\":\"444\",\ "options\":null,\"sortNum\":8,\"status\":\"1\",\"clearable\":true,\"templates\":\"col-sm-6\"},{\"createBy\":70446,\"crea teDate\":1622092153440,\"updateBy\":70446,\"updateDate\":1622092153440,\"remarks\":null,\"id\":4039,\"templateId\":61,\" FieldId \ ": 129, \" fieldName \ ": \" demand time \ ", \ "fieldType \", \ "5 \" and \ "fieldLength \ fieldSetup" : 1, \ "\", null, \ "isRequired \", \ "\", \ "is 1 Visible \ ": \" 1 \ ", \ "isFixed \" : \ "1 \" and \ "" reason \", null, \ "lineAccounted \", null, \ "value \", \ "the T16 2021-06-22:00:00, 000 z \" and \ "option s\":null,\"sortNum\":10,\"status\":\"1\",\"templates\":\"col-sm-6\"}]'; jdList = JSON.parse(str1); console.log(jdList); // Output two pieces of the arrayCopy the code

String transfer object
var jdData = {}; var str2 = '{\"createBy\":70446,\"createDate\":1622092153440,\"updateBy\":70446,\"updateDate\":1622092153440,\"remarks\":null,\"id\ ":4037,\"templateId\":61,\"fieldId\":132,\"fieldName\":\"JD\",\"fieldType\":\"1\",\"fieldLength\":999,\"fieldSetup\":nul l,\"isRequired\":\"1\",\"isVisible\":\"1\",\"isFixed\":\"1\",\"reason\":null,\"lineAccounted\":null,\"value\":\"444\",\" options\":null,\"sortNum\":8,\"status\":\"1\",\"clearable\":true,\"templates\":\"col-sm-6\"}'; jdData = JSON.parse(str2); console.log(jdList); // Output objectsCopy the code

Application scenarios

The use of JSON. Stringify ()

1. If the RequestMapping parameter list corresponding to Java in the background is a single object, and there are multiple transfers in the foreground, it needs to be processed through json.stringify (), otherwise the parameter parsing error will occur. 2. Determine whether the array contains an object, or whether the objects are equal.

/ / determine whether an array containing a certain object var data = [{name: '123'}, {name: "ABC"}, {name: '@ # $}]. var value = {name:'abc'}; JSON.stringify(data).indexOf(JSON.stringify(value)) ! = = 1; //trueCopy the code
Var a = [a,b,c], var b = [a,b,c]; JSON.stringify(a) === JSON.stringify(b); //trueCopy the code

3, by having the localStorage/sessionStorage object format of data may be stored. LocalStorage and sessionStorage by default can only be stored string types of data, but in actual development need to store more data for the object type, you can use json. The stringify () will object to a string and then cache storage, at the time of taking the cached data, This can be done in conjunction with json.parse() to turn data back into objects.

/ / cache the data function setStorage (key, value) {window. LocalStorage. SetItem (key, JSON stringify (value)); }; / / remove the cache data function getStorage (key) {let value = JSON. Parse (window. LocalStorage. The getItem (key)); return value; };Copy the code

Implement a deep copy of objects. During development, it is common to make a deep copy of the original data for any operation if the original data is not affected. This can be done by using json.stringify () and json.parse ().

Function deepCopy(data) {let _data = json.stringify (data), dataCopy = json.parse (_data); return dataCopy; };Copy the code

5. Compare the use of json.stringify () with the use of toString(). Although both can convert the target value to a string, they are fundamentally different, such as

Let array = [1, 2, 3]; JSON.stringify(array); / / '[1, 2, 3]' array. The toString (); / / 1, 2, 3Copy the code

Then, json.stringify () is more of an object, but toString() converts arrays to strings, but doesn’t do the desired thing on objects like {name:’@#$’}, and toString() is more of a number.

Use of json.parse () :

1. If the foreground requests the background and the background returns a lot of string data, then the foreground page rendering needs to render a lot of string data returned by the background in the form of objects, then it needs to use json.parse () for processing.

2. When using json.parse (), it is important to note that since this method converts a JSON string to an object, the string must conform to the JSON format, that is, the key values must be enclosed in double quotes, otherwise an error will be reported.

The above is all of this chapter, welcome to pay attention to three shopkeeper’s wechat public number “program ape by three shopkeeper”, three shopkeeper’s Sina Weibo “three shopkeeper 666”, welcome to pay attention!