Home > Article > Web Front-end > javascript how to json content
JavaScript is a programming language widely used in web development, and it is also a skill that must be mastered in front-end development work. During the development process, JavaScript can be used to achieve dynamic interactive effects, thereby improving the user experience of the website. Among them, JSON is a special data format that is widely used in JavaScript development. This article will introduce how to process JSON data in JavaScript.
1. What is JSON
The full name of JSON is JavaScript Object Notation, which is a lightweight text-based data exchange format. Data in JSON format can be represented as a JavaScript object, which is similar to the JavaScript object format. Data in JSON format has the following characteristics:
2. JSON processing in JavaScript
JavaScript provides some built-in functions for processing JSON data. Below we will introduce the usage of these functions respectively.
The JSON.parse() function is used to convert JSON-formatted strings into JavaScript objects. The syntax is as follows:
JSON.parse(text[,reviver])
Among them, text represents the JSON format string to be parsed, and reviver is an optional parameter, used to process the parsed JavaScript object, which can be a function or a filter array.
Example:
var jsonStr = '{"name": "张三", "age":20}'; var jsonObj = JSON.parse(jsonStr); console.log(jsonObj.name); //输出 "张三" console.log(jsonObj.age); //输出 20
The JSON.stringify() function is used to convert JavaScript objects into JSON format characters string. The syntax is as follows:
JSON.stringify(value[,replacer[,space]])
Among them, value represents the JavaScript object to be converted into a JSON format string, replacer is an optional parameter, used to control the converted result, which can be a function or an array, and space is Optional parameter that specifies the number of whitespace characters to indent the result string.
Example:
var jsonObj = {"name":"张三","age":20}; var jsonStr = JSON.stringify(jsonObj); console.log(jsonStr); //"{"name":"张三","age":20}"
When needed between different web pages When passing a JavaScript object, you can convert the object into a JSON format string, and then convert the JSON format string into a JavaScript object after transmission. An example is as follows:
//将 对象转化为JSON格式字符串 var jsonObj = {"name":"张三","age":20}; var jsonStr = JSON.stringify(jsonObj); //传输jsonStr之后 //将JSON格式字符串转化为对象 var jsonObjNew = JSON.parse(jsonStr); console.log(jsonObjNew.name); //输出 "张三" console.log(jsonObjNew.age); //输出 20
The above is the relevant introduction to processing JSON format data in JavaScript. I hope it will be helpful to your work.
The above is the detailed content of javascript how to json content. For more information, please follow other related articles on the PHP Chinese website!