Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use JSON in JavaScript

Shulou Source: shulou.com Published: 2022-06-01 03:32:21 09月22日 Update

This article mainly shows you "how to use JSON in JavaScript", the content is easy to understand, clear, hope to help you solve doubts, the following let the editor lead you to study and learn "how to use JSON in JavaScript" this article.

JSON1.stringify ()

Used to serialize js objects into JSON strings

Var person= {name: "xiaoming" age:12} var json=JSON.stringify (person); / / {"name": "xiaoming", "age": 12}

Stringify () can accept two parameters in addition to objects. The first parameter is a filter, which can be an array collection of object properties or a function. The second parameter is an option indicating whether to retain indentation in the JSON string.

Array filter:

Json=JSON.stringify (person, ['name']); / / {"name": "xiaoming"}

Function filter:

Json=JSON.stringify (person,function (key,value) {switch (key) {case "name": return value+ ", wang"; case "age": return undefined; default: return value;}); / / {"name": "xiaoming,wang"}

Note that if the function returns undefined, this property is ignored

String indentation:

Json=JSON.stringify (person,null,4); {"name": "xiaoming", "age": 12} 2.toJSON ()

Add the toJSON () method to the object:

Var person= {name: "xiaoming", age:12, toJSON:function () {return this.name+ "is" + this.age;}} json=JSON.stringify (person); console.log (json); / / "xiaoming is 12" 3.parse ()

In addition to accepting a json string, parse () can also accept a function argument. This function accepts two values, a key and a value

Var person=JSON.parse ('{"name": "xiaoming", "age": 12}'); var person=JSON.parse ('{"name": "xiaoming", "age": 12}', function (key,value) {if (key== "age") {return value+10;} else {return value;}); these are all the contents of the article "how to use JSON in JavaScript". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Tags: Function parameter character string object content article filter attribute array learning help sequence method easy to understand more organization knowledge ribbon industry Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia Xiaomi MySQL vpn Huawei