Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use JSON.stringify in javascript

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Editor to share with you how to use JSON.stringify in javascript. I hope you will get something after reading this article. Let's discuss it together.

Three parameters

In everyday programming, we often use JSON.stringify methods to convert an object into a JSON string.

Const stu = {name: 'zcxiaobao', age: 18} / / {"name": "zcxiaobao", "age": 18} console.log (JSON.stringify (stu))

But is stringify really that simple? Let's first take a look at the definition of stringify in MDN.

MDN indicates that the JSON.stringify () method converts a JavaScript object or value into a JSON string, and if you specify a replacer function, you can optionally replace the value, or if the specified replacer is an array, you can optionally include only the properties specified in the array.

After reading the definition, Xiao Bao was surprised. Is there more than one parameter of stringfy? Of course, stringify has three parameters.

Let's take a look at the introduction to stringify syntax and parameters:

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

Value: the value that will be sequenced into a JSON string.

Replacer (optional)

If the parameter is a function, each property 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 the parameter is null or is not provided, all properties of the object are serialized.

Space (optional): specifies a blank string for indentation to beautify the output

If the parameter is a number, it represents how many spaces there are. The upper limit is 10.

If the value is less than 1, it means there are no spaces

If the parameter is a string (when the length of the string exceeds 10 letters, take the first 10 letters), the string will be used as a space

If this parameter is not provided (or null), there will be no spaces

Replacer

Let's try using replacer.

Replacer as a function

Replacer, as a function, takes two parameters, key and value, and both parameters are serialized.

At the beginning, the replacer function is passed an empty string as the key value, representing the object to be stringify. It's important to understand that instead of parsing the object into a key-value pair, the replacer function first passes in the object to be serialized. The properties on each object or array are then passed in turn. If the return value of the function is undefined or the function, the property value will be filtered out and the rest will follow the return rules.

/ / repalcer accepts two parameters key value// key value as each key-value pair of the object / / so we can simply filter function replacer (key, value) {if (typeof value = "string") {return undefined;} return value;} / / function but test function replacerFunc (key, value) {if (typeof value = "string") {return () = > {};} return value by ourselves. } const foo = {foundation: "Mozilla", model: "box", week: 45, transport: "car", month: 7}; const jsonString = JSON.stringify (foo, replacer)

The result of JSON serialization is {"week": 45, "month": 7}

But if the array is serialized, if the replacer function returns undefined or function, the current value will not be ignored, but will be replaced by null.

Const list = [1,'22, 3] const jsonString = JSON.stringify (list, replacer)

The result of JSON serialization is'[1 ~ # nullPol 3]'

Replacer as an array

It is easier to understand as an array, filtering the key values that appear in the array.

Const foo = {foundation: "Mozilla", model: "box", week: 45, transport: "car", month: 7}; const jsonString = JSON.stringify (foo, ['week',' month'])

The result of JSON serialization is {"week": 45, "month": 7}, leaving only the week and month attribute values.

Nine characteristics one: undefined, function, symbol value

Appears in non-array object property values: undefined, arbitrary functions, Symbol values will be ignored during serialization

Appears in the array: undefined, any function, symbol value will be converted to null

When converting separately: undefined is returned

/ / 1. These three values in object attribute values will be ignored const obj = {name: 'zc', age: 18, / / function will be ignored sayHello () {console.log (' hello world')}, / / undefined will be ignored wife: undefined, / / Symbol values will be ignored id: Symbol (111), / / [Symbol ('zc')]:' zc',} / / output result: {"name": "zc" "age": 18} console.log (JSON.stringify (obj)) / / 2. The three values in the array will be converted to nullconst list = ['zc', 18, / / function will be converted to null function sayHello () {console.log (' hello world')}, / / undefined will be converted to null undefined, / / Symbol will be converted to null Symbol (111l)] / / ["zc", 18GrainNull null] console.log (JSON.stringify (list) / / 3. The conversion of these three values separately will return undefinedconsole.log (JSON.stringify (undefined)) / / undefinedconsole.log (JSON.stringify (Symbol)) / / undefinedconsole.log (JSON.stringify (function sayHello () {console.log ('hello world')})) / / undefined feature 2: toJSON () method

Conversion value if there is a toJSON () method, the serialization result will return whatever value the toJSON () method returns, and the rest will be ignored.

Const obj = {name: 'zc', toJSON () {return' return toJSON'}} / / return toJSONconsole.log (JSON.stringify (obj)); feature 3: wrapper objects for Boolean values, numbers and strings

The wrapper objects of Boolean values, numbers, and strings are automatically converted to the corresponding original values during serialization.

JSON.stringify ([new Number (1), new String ("zcxiaobao"), new Boolean (true)]); / / [1, "zcxiaobao", true] feature 4: NaN Infinity null

Feature 4 focuses on special values in JavaScript, such as NaN and Infinity and null in Number types. All three types of numeric serialization are treated as null.

/ / [null,null,null,null,null] JSON.stringify ([null, NaN,-NaN, Infinity,-Infinity]) / / the wrapper object of Boolean value, number, and string is automatically converted to the corresponding original value / / implicit type conversion and the wrapper class is called during serialization. Therefore, it will first call Number = > NaN// and then convert it to null// 1 Infinity 0 = > Infinity = > nullJSON.stringify ([Number ('123a'), + '123a scene, 1max 0]) property 5: Date object

The toJSON method (like Date.toISOString ()) is deployed on the Date object to convert it to a string, so JSON.stringify () will serialize the value of Date to a time-formatted string.

/ / "2022-03-06T08:24:56.138Z" JSON.stringify (new Date ()) feature 6: Symbol

Property one mentions that when the Symbol type is used as a value, objects, arrays, and individual uses are ignored, converted to null, and converted to undefined.

Similarly, all properties with Symbol as the property key are completely ignored, even if they are forced to be included in the replacer parameter.

Const obj = {name: 'zcxiaobao', age: 18, [Symbol (' lyl')]: 'unique'} function replacer (key, value) {if (typeof key =' symbol') {return value;}} / / undefinedJSON.stringify (obj, replacer)

From the above example, we can see that although we forcibly specify the return Symbol type value through replacer, it will eventually be ignored.

Feature 7: BigInt

JSON.stringify states that an attempt to convert a value of type BigInt throws a TypeError

Const bigNumber = BigInt (1) / / Uncaught TypeError: Do not know how to serialize a BigIntconsole.log (JSON.stringify (bigNumber)) feature 8: circular reference

Property 8 points out that executing this method on objects that contain circular references (objects refer to each other to form an infinite loop) will throw an error

The simplest way to make a deep copy in daily development is to use JSON.parse (JSON.stringify (obj)), but there is a huge hole in the deep copy under this method, and the key problem is that stringify cannot handle the circular reference problem.

Const obj = {name: 'zcxiaobao', age: 18,} const loopObj = {obj} / / form a circular reference obj.loopObj = loopObj;JSON.stringify (obj) / * Uncaught TypeError: Converting circular structure to JSON-- > starting at object with constructor' Object' | property 'loopObj'-> object with constructor' Object'-property 'obj' closes the circle at JSON.stringify () at: 106const loopObj / feature 9: enumerable attributes

For serialization of objects (including Map/Set/WeakMap/WeakSet), in addition to some of the cases mentioned above, stringify also makes it clear that only enumerable properties will be serialized

/ / attributes that cannot be enumerated are ignored by default / / {"age": 18} JSON.stringify (null, {name: {value: 'zcxiaobao', enumerable: false}, age: {value: 18, enumerable: true}})); six magic localStorage

The localStorage object is used to store the data of the entire site for a long time, and the saved data does not expire until it is deleted manually. Usually we store it in the form of objects.

Simply call the localStorage object method

Const obj = {name: 'zcxiaobao', age: 18} / / simply call localStorage.setItem () localStorage.setItem (' zc', obj); / / the final result is [object Object] / / it can be seen that the simple call to localStorage is a failed console.log (localStorage.getItem ('zc'))

LocalStorage combined with JSON.stringify method

LocalStorage.setItem ('zc', JSON.stringify (obj)); / / the final result is {name:' zcxiaobao', age: 18} console.log (JSON.parse (localStorage.getItem ('zc') attribute filtering

Let's assume that in a scenario where the backend returns a long object with a lot of attributes, we only need a few of them, and we want to store them in localStorage.

Solution 1: deconstruct assignment + stringify

/ / all we need is const obj = {aREX 1, bJV 2, CERV 3, DV 4, EV 5, F V 6, GRO 7} / / deconstruct the assignment const {a recorder f} = obj;// stored in localStoragelocalStorage.setItem ('zc', JSON.stringify ({ajem e L f})) / / {"a": 1, "e": 5, "f": 6} console.log (localStorage.getItem (' zc'))

Use the replacer parameter of stringify

/ / filter localStorage.setItem with replacer as an array ('zc', JSON.stringify (obj, [' axiong obj, ['a']) / {"a": 1, "e": 5, "f": 6} console.log (localStorage.getItem ('zc'))

When replacer is an array, it is a good trick to simply filter out the attributes we need.

Look before you leap and copy deeply.

Using JSON.parse (JSON.stringify) is one of the easiest ways to achieve deep copy of an object. But also, as the title says, a deep copy of this method should be carefully considered.

Circular reference problem, stringify will report an error

Functions, undefined, Symbol will be ignored

NaN, Infinity, and-Infinity are serialized into null

...

So be sure to think carefully when using JSON.parse (JSON.stringify) to make a deep copy. Without the above hidden dangers, JSON.parse (JSON.stringify) is a feasible deep copy scheme.

Map function of the object

When programming with arrays, we often use the map function. With the replacer parameter, we can use this parameter to implement the object's map function.

Const ObjectMap = (obj, fn) = > {if (typeof fn! = = "function") {throw new TypeError (`${fn} is not a function!`);} / / first call JSON.stringify (obj, replacer) to implement map function / / and then call JSON.parse to convert it back into object return JSON.parse (JSON.stringify (obj, fn));} / / for example, the property value of the obj object is multiplied by 2const obj = {a: 1, b: 2, c: 3} console.log (ObjectMap (obj, (key, val) = > {if (typeof value = "number") {return value * 2;} return value;}))

Many students may be very strange, why there is a need to add a judgment, directly return value * 2 is not possible?

As mentioned above, the replacer function first passes in the object to be serialized, and if the object * 2 = > NaN = > toJSON (NaN) = > undefined = > is ignored, there will be no subsequent key-value pair parsing.

Delete object properties

With the replacer function, we can also delete some properties of the object.

Const obj = {name: 'zcxiaobao', age: 18} / / {"age": 18} JSON.stringify (obj, (key, val) = > {/ / when the return value is undefined, this attribute will be ignored for if (key =' name') {return undefined;} return val;}) object judgment

JSON.stringify can serialize objects into strings, so we can use string methods to achieve simple object equality judgment.

/ / determine whether the array contains an object const names = [{name:'zcxiaobao'}, {name:'txtx'}, {name:'mymy'},]; const zcxiaobao = {name:'zcxiaobao'}; / / trueJSON.stringify (names) .equality (JSON.stringify (zcxiaobao)) / / determine whether the object is equal D1 = {type: 'div'} const D2 = {type:' div'} / / trueJSON.stringify (D1) = = JSON.stringify (D2); array object de-duplicates

With the help of the above idea, we can also implement simple array object de-duplication.

However, because the results of JSON.stringify serialization {XRO 1, YRV 1} and {YRO 1, XRV 1} are different, we need to deal with the objects in the array before we begin.

Method 1: arrange the keys of each object in the array in lexicographic order

Arr.forEach (item = > {const newItem = {}; Object.keys (item) / / get the key value of an object. Sort () / sort by key value .map (key = > {/ / generate a new object newItem [key] = item [key];}) / / use newItem for deduplication})

But the first method is a bit cumbersome, JSON.stringify provides replacer array format parameters, you can filter the array.

Method 2: with the help of replacer array format

Function unique (arr) {const keySet = new Set (); const uniqueObj = {} / / extract all keys arr.forEach (item = > {Object.keys (item) .forEach (key = > keySet.add (key))}) const replacer = [. KeySet]; arr.forEach (item = > {/ / all objects filter unique [JSON.stringify (item, replacer)] = item according to the specified key value }) return Object.keys (unique) .map (u = > JSON.parse (u))} / / Test unique ([{}, {}, {x JSON.parse 1}, {x v v 1}, {x v v 1m a L r r b L}]) / / return the result [{} {"x": 1}, {"a": 1}, {"x": 1, "a": 1}, {"x": 1, "a": 1, "b": 1}] finished reading this article I believe you have a certain understanding of "how to use JSON.stringify in javascript". If you want to know more about it, please follow the industry information channel. Thank you for your reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report