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

What are the skills of using JSON in JavaScript

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

Share

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

This article mainly explains "what are the skills of using JSON in JavaScript". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "what are the skills of using JSON in JavaScript"?

1. Formatting

The default serializer also shrinks the JSON, which looks ugly

Const user = {name: 'John', age: 30, isAdmin: true, friends: [' Bob', 'Jane'], address: {city:' New York', country: 'USA'}}; console.log (JSON.stringify (user)) / = > {"name": "John", "age": 30, "isAdmin": true, "friends": ["Bob", "Jane"], "address": {"city": "New York", "country": "USA"}}

JSON.stringify also has a built-in formatter!

Console.log (JSON.stringify (user, null, 2)) / / {/ / "name": "John", / / "age": 30 Bob / isAdmin: true,// "friends": [/ / "Bob", / / "Jane" / /], / / "address": {/ / "city": "New York", / / "country": "USA" / /} / /}

(if you want to know what that null is, we'll talk about it later)

In this example, the JSON format is 2 indented spaces.

We can also specify custom characters for indentation.

Console.log (JSON.stringify (user, null, 'lol')); / {/ / lol "name": "John", / / lol "age": 30 lol isAdmin: true,// lol "friends": [/ / lollol "Bob", / / lollol "Jane" / / lol], / / lol "address": {/ / lollol "city": "New York", / / lollol "country": "USA" / / lol} / /} 2. Hide some attributes in the serialized data

The second parameter of JSON.stringify, which is largely unknown. It is called replacer, and it is a function or array that determines which data is retained in the output and which is not.

This is a simple example where we can hide the password user.

Const user = {name: 'John', password:' 12345, age: 30}; console.log (JSON.stringify (user, (key, value) = > {if (key = 'password') {return;} return value;})

This is the output:

{"name": "John", "age": 30}

We can further ReFactor:

Function stripKeys (... keys) {return (key, value) = > {if (keys.includes (key)) {return;} return value;};} const user = {name: 'John', password:' 12345, age: 30, gender: 'male'}; console.log (JSON.stringify (user, stripKeys (' password', 'gender')

Output:

{"name": "John", "age": 30}

You can also pass an array to get only certain keys:

Const user = {name: 'John', password:' 12345, age: 30} console.log (JSON.stringify (user, ['name',' age']))

Output the same thing.

This also applies to arrays. If you have a lot of cakes:

Const cakes = [{name: 'Chocolate Cake', recipe: [' Mix flour, sugar, cocoa powder, baking powder, eggs, vanilla, and butter', 'Mix in milk',' Bake at 350 degrees for 1 hour', / /...], ingredients: ['flour',' sugar', 'cocoa powder',' baking powder' 'eggs',' vanilla', 'butter']}, / / tons of these]

We can easily do the same thing, and the replacement will be applied to each cake:

Const cakes = [{name: 'Chocolate Cake', recipe: [' Mix flour, sugar, cocoa powder, baking powder, eggs, vanilla, and butter', 'Mix in milk',' Bake at 350 degrees for 1 hour', / /...], ingredients: ['flour',' sugar', 'cocoa powder',' baking powder' 'eggs',' vanilla', 'butter']}, / / tons of these] Console.log (JSON.stringify (cakes, ['name']))

We got this:

[{"name": "Chocolate Cake"}, {"name": "Vanilla Cake"},...]

3. Create a custom output format using toJSON

If an object implements the toJSON function, JSON.stringify will use it to serialize the data.

Consider this:

Class Fraction {constructor (n, d) {this.numerator = n; this.denominator = d;}} console.log (JSON.stringify (new Fraction (1,2)

This will output {"numerator": 1, "denominator": 2}. But what if we want to replace it with a string?

Enter toJSON

Class Fraction {constructor (n, d) {this.numerator = n; this.denominator = d;} toJSON () {return `${this.numerator} / ${this.denominator}`} console.log (JSON.stringify (new Fraction (1,2)

JSON.stringify respects toJSON property and output "1Compact 2".

4. Recover data

Our above score example works well. But what if we want to recover the data? When we parse JSON again, wouldn't it be cool if the score could magically return? We can!

Enter the Resurrection!

Class Fraction {constructor (n, d) {this.numerator = n; this.denominator = d;} toJSON () {return `${this.numerator} / ${this.denominator}`} static fromJSON (key, value) {if (typeof value = 'string') {const parts = value.split (' /') .map (Number); if (parts.length = 2) return new Fraction (parts);} return value }} const fraction = new Fraction (1,2); const stringified = JSON.stringify (fraction); console.log (stringified); / / "1stringified 2" const revived = JSON.parse (stringified, Fraction.fromJSON); console.log (revived); / / Fraction {numerator: 1, denominator: 2}

We can pass the second argument, JSON.parse, to specify the reviver function. The job of the restorer is to "restore" the serialized data back to its original form. Here, we pass a reviver, which is the static fromJSON property Fraction of the class.

In this case, reviver checks to see if the value is a valid score, and if so, it creates a new Fraction object and returns it.

Interesting fact: this feature is used for built-in Date objects. Try to find Date.prototype.toJSON

That's why it works:

Console.log (JSON.stringify (new Date () / / = > '2022-03-01T06:28:41.308Z'

To restore the date, we can use JSON.parse:

Function reviveDate (key, value) {const regex = / ^\ d {4} -\ d {2} -\ d {2} T\ d {2}:\ d {2}:\ d {2} (\.\ d {1,}} |) Z return value; if (typeof value = = "string" & & regex.test (value)) {return new Date (value);} return value } console.log (JSON.parse ('"2022-03-01T06:28:41.308Z", reviveDate)) / / = > Tue Mar 01 2022 06:28:41 GMT-0700 (Pacific Daylight Time) 5. Use revivers to hide data

Like parsers, restorers can also be used to hide data. It works in the same way.

This is an example:

Const user = JSON.stringify ({name: 'John', password:' 12345, age: 30}); console.log (JSON.parse (user, (key, value) = > {if (key = 'password') {return;} return value;}))

This is the output:

{name: 'John', age: 30}

At this point, I believe you have a deeper understanding of "what are the skills for using JSON in JavaScript?" you might as well do it in practice. 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