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 in JavaScript

2025-04-12 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

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!

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