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

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

Share

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

This article mainly explains "how to use JSON.stringify". Friends who are interested might as well take a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn how to use JSON.stringify.

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

The replacer parameter can be a function or an array. As a function, it has two parameters, key and value, both of which are serialized.

It is worth noting that at the beginning, the replacer function is passed an empty string as the key value, and value represents the object to be stringify. The properties on each object or array are then passed in turn.

Generally speaking, the replacer parameter is used to manually ignore some properties that do not want to be serialized, which is somewhat similar to the function of a filter.

Var foo = {id: 1, name: "sf", age: 18,}; / / as a function, ignore this attribute value JSON.stringify (foo, (key, value) = > {if (typeof value = = "string") {return undefined;} return value;}) when the function does not return a value or the return value is undefined. / / {"id": 1, "age": 18} / / as an array, the value of the array represents the attribute name JSON.stringify (foo, ['id', "name"]) to be serialized into a JSON string; / / {"id": 1, "name": "sf"} space parameter

The space parameter is used to control the spacing within the resulting string. If it is a number, each level indents more spaces of the numeric value (up to 10 spaces) than the previous level; if it is a string, each level indents the string (or the first 10 characters of the string) more than the previous level. The actual use is basically used to beautify the output.

Let a = JSON.stringify ({a: 1, b: 2}, null, 2); let b = JSON.stringify ({a: 1, b: 2}, null, ""); console.log (a = = b); / / trueJSON.stringify ({a: 1, b: 2}, null, "-"); / / {/ /-- "a": 1. Undefined, symbol value, function description.

Appears in object property values: undefined, symbol value, function, and will be ignored during serialization

Appears in the array: undefined, symbol values, functions are converted to null

When converting separately: undefined is returned

Const obj = {a: "a", b: undefined, c: Symbol (), d: function () {},}; JSON.stringify (obj) / / {"a": "a"} const arry = [undefined, Symbol ("c"), function () {}]; JSON.stringify (arry); / / [null,null,null] JSON.stringify (undefined); / / undefinedJSON.stringify (Symbol (111)); / / undefinedJSON.stringify (function () {}); / / undefined2. Properties of non-array objects are not guaranteed to appear in serialized strings in a specific order.

As mentioned in the first feature, JSON.stringify () ignores some special values when serializing, so there is no guarantee that serialized strings will appear in a specific order (except arrays).

3. The wrapper objects of Boolean values, numbers, and strings are automatically converted to the corresponding original values JSON.stringify ([new Boolean (true), new Number (1), new String ("a")]) during serialization; / / [true,1, "a"] 4. Converted value if there is a toJSON () method, this method defines what value will be serialized const obj = {a: "aaa", toJSON () {return "hello world";},}; JSON.stringify (obj); / / "hello world" 5. Executing this method on objects that contain circular references (objects that reference each other to form an infinite loop) throws an error. Const obj = {name: "loopObj",}; const loopObj = {obj,}; / / objects form a circular reference to form a closed loop obj.loopObj = loopObj;JSON.stringify (obj); / / TypeError: Converting circular structure to JSON6. All properties with symbol as the property key are completely ignored, even if they are forcibly included in the replacer parameter.

. Executing this method on objects that contain circular references (objects that reference each other to form an infinite loop) throws an error.

Const obj = {a: "aaa", [Symbol ("foo")]: "foo",}; JSON.stringify (obj); / / {"a": "aaa"} JSON.stringify (obj, function (k, v) {if (typeof k = = "symbol") {return "a symbol";}}); / / undefined7. The date calls toJSON () to convert it to a string string (the same as Date.toISOString ()), so it is treated as a string. JSON.stringify ({date: new Date ("2022-02-02"),}) / / {"date": "2022-02-02T00:00:00.000Z"} 8. Values in NaN and Infinity formats and null are treated as null. JSON.stringify ([NaN, Infinity, 1 / 0, Number ("a")]); / / [null,null,null,null] 9. Other types of objects, including Map/Set/WeakMap/WeakSet, serialize only enumerable properties. / / attributes that cannot be enumerated are ignored by default: JSON.stringify (Object.create (null, {value: "x", enumerable: false}, y: {value: "y", enumerable: true},}); / / "{" y ":" y "}" apply localStorage

Key-value pairs in localStorage are always stored as strings, so when we need to store an object in localStorage, we can only use JSON.stringify to convert it into a string and use the JSON.parse method to get it.

Const userInfo = {user: "admin"}; localStorage.setItem ("userInfo", JSON.stringify (userInfo)); JSON.parse (localStorage.getItem ("userInfo")); / / {user: 'admin'} object deep copy

Using JSON.parse (JSON.stringify) is the simplest and roughest way to make a deep copy of an object. However, there are some problems due to some features of JSON.stringify, such as:

Undefined, Symbol, functions are ignored in the object and serialized into null in the array.

NaN, Infinity, and-Infinity are serialized into null.

Stringify will report an error due to a circular reference problem.

When it is determined that the above does not exist, consider using JSON.parse (JSON.stringify) for deep copy.

Attribute filtering

When the interface returns a lot of data and we only want to store a few attributes, it is a good trick to filter attributes through the replacer function.

Var foo = {id: 1, name: "sf", age: 18,}; localStorage.setItem ("user", JSON.stringify (foo, ["id", "name"])); localStorage.getItem ("user"); / / {"id": 1, "name": "sf"} so far, I believe you have a deeper understanding of "how to use JSON.stringify", you might as well do it! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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