Home > Article > Web Front-end > How to use JavaScript’s JSON object
In JavaScript, the JSON object contains two methods: parse() method and stringify() method; using these two methods of the JSON object can realize the mutual conversion of JSON strings and JavaScript objects. The following article will introduce to you how to use JSON objects in JavaScript.
What is JSON in JavaScript?
JSON is a format for storing and transmitting data; a lightweight human-readable collection of data that can be accessed in a logical manner.
JSON can generate and store data from user input; it can transfer data from server to client, from client to server, and from server to server; and it can also build and validate data.
Usage of JSON object
JSON.parse() method
Parse of JSON object The () method can accept a JSON string and convert it into the corresponding JavaScript object, and then return this object. Let's take a look at the basic sentence structure:
JSON.parse(text [,reviver])
text: a string to be parsed into JSON;
reviver: an optional parameter that specifies how to convert the text originally generated by parsing before returning it value.
Example:
<script> var json = '{ "学号":"01", "姓名":"小华", "年龄":20 }'; var student = JSON.parse(json); //全部输出 console.log(student); //单个输出 console.log("学号:"+student.学号); console.log("姓名:"+student.姓名); console.log("年龄:"+student.年龄); </script>
The running effect is as follows: Let’s take a look at the output
##JSON.stringify() method
The stringify() method of the JSON object can convert the JavaScript value into the corresponding JSON string and then return the JSON string. Let's take a look at the basic sentence structure:Json.stringify(value [,replacer [,space]])value: Specify the js value to be converted into a JSON string. Replacer: Optional parameter that can change the behavior of the stringification process. If the replacer function is specified, it replaces the value; if the replacer array is specified, it contains only the specified properties. space: Optional parameter, a String or Number object used to insert spaces into the output JSON string for easier reading. Example: Convert JavaScript string objects and array objects to JSON strings
//JavaScript字符串对象 var json = { 学号:"01", 姓名:"小华", 年龄:20 }; var student = JSON .stringify(json); console.log(student); //JavaScript数组对象 var arr = [ "php", "mysql", "javascript"]; var bc = JSON .stringify(arr); console.log(bc);Output: Summary: That’s it The entire content of this article is hoped to be helpful to everyone's study.
The above is the detailed content of How to use JavaScript’s JSON object. For more information, please follow other related articles on the PHP Chinese website!