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-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article is about how to use JSON.stringify (). The editor thinks it is very practical, so I hope you can get something after reading this article. Let's take a look at it with the editor.

JSON is a lightweight data format that can easily represent complex data structures. The JSON object has two methods: stringify () and parse (). In simple cases, these two methods can serialize JavaScript into JSON strings and parse JSON to native JavaScript values, respectively.

This article focuses on the use of JSON.stringify () and matters needing attention.

I. method of use 1. Basic usage

JSON.stringify () serializes a JavaScript object into a JSON string.

Let json1 = {title: "Json.stringify", author: ["Boating in the waves"], year: 2021}; let jsonText = JSON.stringify (json1)

By default, JSON.stringify () outputs JSON strings that do not contain spaces or indentation, so the value of jsonText is like this:

"{" title ":" Json.stringify "," author ": [" Boating in the waves "]," year ": 2021}"

When serializing a JavaScript object, all functions and prototype members are intentionally omitted from the result. In addition, any property with a value of undefined is also skipped. The end result is a representation that all instance properties are valid JSON data types.

The JSON.stringify () method accepts a total of three parameters, two of which are optional (the second and third, respectively). These two optional parameters can be used to specify other ways to serialize JavaScript objects. The second parameter is the filter, which can be an array or function; the third parameter is the option to indent the resulting JSON string. Using these parameters alone or in combination gives you more control over JSON serialization.

2. The second parameter-filter

If the second parameter is an array, the result returned by JSON.stringify () will contain only the object properties listed in that array. For example, the following example:

Let json1 = {title: "Json.stringify", author: ["Boating in the waves"], year: 2021, like: 'frontend', weixin:' frontJS'}; let jsonText = JSON.stringify (json1, ['weixin'])

In this example, the second argument to the JSON.stringify () method is an array containing a string: "weixin". It corresponds to the property in the object to be serialized, so the resulting JSON string contains only this property:

"{" weixin ":" frontJS "}"

If the second parameter is a function, the behavior is different. The provided function takes two parameters: the property name (key) and the attribute value (value). Based on this key, you can decide what to do with the corresponding attribute. This key is always a string, but an empty string if the value does not belong to a key / value pair.

Const students = [{name: 'james', score: 100,}, {name:' jordon', score: 60,}, {name: 'kobe', score: 90,}]; function replacer (key, value) {if (key =' score') {if (value = 100) {return'slots;} else if (value > = 90) {return 'A' } else if (value > = 70) {return'Brough;} else if (value > = 50) {return'Craft;} else {return'Emission;}} return value;} console.log (JSON.stringify (students, replacer, 4))

In the above code, we replace the score from the percentile system to the grade level through replacer.

It is worth noting that if the second argument of stringify is a function, then its return value is undefined, then the corresponding property will not be serialized, and if other values are returned, the returned value will replace the original value for serialization.

3. The third parameter-string indentation

The third parameter of the JSON.stringify () method controls indentation and spaces. When this parameter is numeric, it represents the number of spaces for each level of indentation. For example, indent 4 spaces per level, you can do this:

Let json1 = {title: "Json.stringify", author: ["Boating in the waves"], year: 2021}; let jsonText = JSON.stringify (json1, null, 4)

The resulting jsonText format is as follows:

{"title": "Json.stringify", "author": ["Boating in the waves"], "year": 2021}

JSON.stringify () considers both data conversion and ease of reading when dealing with data, but the convenience of reading is often ignored.

4. ToJSON () method-- Custom JSON serialization

Sometimes, objects need custom JSON serialization on top of JSON.stringify (). At this point, you can add the toJSON () method to the object to be serialized, based on which the appropriate JSON representation is returned.

The following object adds a toJSON () method for custom serialization:

Let json1 = {title: "Json.stringify", author: ["Boating in the waves"], year: 2021, like: 'frontend', weixin:' frontJS', toJSON: function () {return this.author}}; console.log (JSON.stringify (json1)); / / ["Boating in the waves"]

Note that the arrow function cannot be used to define the toJSON () method. The main reason is that the lexical scope of the arrow function is global, which is not appropriate in this case.

Second, use scenario 1 to determine whether the array contains an object, or whether the objects are equal. / / determine whether the array contains an object let data = [{name:' rowing in the waves'}, {name:' front-end craftsmen'}, {name:' front-end development'},], val = {name:' rowing in the waves'}; console.log (JSON.stringify (data) .indexOf (JSON.stringify (val))! = =-1); / / true

We can also use the JSON.stringify () method to determine whether two objects are equal.

/ / determine whether the object is equal let obj1 = {a: 1, b: 2} let obj2 = {a: 1, b: 2,} console.log (JSON.stringify (obj1) = JSON.stringify (obj2)) / / true

However, this approach has great limitations, if the object adjusts the order of the keys, it will make a mistake!

/ / after adjusting the position of the object key let obj1 = {a: 1, b: 2} let obj2 = {b: 2, a: 1,} console.log (JSON.stringify (obj1) = JSON.stringify (obj2)) / / false2, when using localStorage/sessionStorage

LocalStorage/sessionStorage can only store strings by default, but in actual development, we often need to store object types, so we need to use json.stringify () to convert the object into a string when storing, and use json.parse () to return the object when fetching the local cache.

/ / storing data function setLocalStorage (key,val) {window.localStorage.setItem (key, JSON.stringify (val));}; / fetching data function getLocalStorage (key) {let val = JSON.parse (window.localStorage.getItem (key)); return val;}; / / testing setLocalStorage ('Test', [' front-end craftsman', 'sailing in the waves']); console.log (getLocalStorage ('Test'))

LocalStorage

3. Implement deep copy of object

In development, sometimes afraid of affecting the original data, we often copy a copy of the data to do any operation, using JSON.stringify () and JSON.parse () to achieve deep copy is a very good choice.

Let arr1 = [1,3, {username: 'kobe'}]; let arr2 = JSON.parse (JSON.stringify (arr1)); arr2 [2] .username =' duncan'; console.log (arr1, arr2)

Image.png

This is using JSON.stringify to convert the object into a JSON string, and then parsing the string into an object with JSON.parse. As soon as it goes, new objects come into being, and new objects open up a new stack to achieve deep copy.

Although this method can make deep copies of arrays or objects, it cannot deal with functions and regularities, because after both JSON.stringify and JSON.parse processing, the resulting regularities are no longer regular (become empty objects), and the resulting functions are no longer functions (become null).

Let arr1 = [1,3, function () {}, {username: 'kobe'}]; let arr2 = JSON.parse (JSON.stringify (arr1)); arr2 [3] .username =' duncan'; console.log (arr1, arr2)

Matters needing attention in use

Although JSON.stringify () is very powerful, some properties cannot be stringify, so you should pay attention to the following situations in development to avoid some unexpected BUG.

1. Among the converted values are NaN and Infinitylet mylet myObj = {name: "boat in the waves", age: Infinity, money: NaN,}; console.log (JSON.stringify (myObj)); / / {"name": "boat in the waves", "age": null, "money": null} JSON.stringify ([NaN, Infinity]) / / [null,null] 2, undefined, any function and symbol value in the converted value

There are two situations:

Arrays, undefined, arbitrary functions, and symbolic values are converted to null during serialization

JSON.stringify ([undefined, function () {}, Symbol (")]); / /'[null,null,null]'

Non-arrays, undefined, arbitrary functions, and symbolic values are ignored during serialization

JSON.stringify ({x: undefined, y: function () {}, z: Symbol (")}); / /'{}'3, circular reference

If the property value of an object refers back to the object itself in some indirect way, it is a circular reference. For example:

Let bar = {a: {c: foo}}; let foo = {b: bar}; JSON.stringify (foo)

In this case, serialization will report an error:

/ / error message Uncaught ReferenceError: foo is not defined at: 3:84, with non-enumerable attribute values

Properties that cannot be enumerated are ignored by default:

Let personObj = Object.create (null, {name: {value: "Boating in the waves", enumerable: false}, year: {value: "2021", enumerable: true},}) console.log (JSON.stringify (personObj)) / / {"year": "2021"} IV. Summary

JSON.stringify () is used to serialize JavaScript objects into JSON strings, and there are options for changing the default behavior to filter or modify the process. However, it should also be noted that some properties cannot be stringify, so developers should avoid these holes!

The above is how to use JSON.stringify (). The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

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