Home > Daily Programming > HTML Knowledge > How to parse json data with js

How to parse json data with js

藏色散人
Release: 2018-12-19 09:46:53
Original
21735 people have browsed it

js parses json data, you can use the JSON.parse() method to achieve parsing. The JSON.parse() method can parse a JSON string and convert it into a JavaScript object.

How to parse json data with js

Now we will introduce to you the implementation method of js parsing json data with a simple code example.

The code example is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>js解析json数据示例</title>
    <script>
 // 将JSON数据存储在JS变量中
 var json = &#39;{"name": "欧阳克", "age": 18, "city": "合肥"}&#39;;

 // 将JSON编码的字符串转换为JS对象
 var obj = JSON.parse(json);

 // 从JS对象访问单个值
 document.write(obj.name + "<br>"); 
 document.write(obj.age + "<br>"); 
 document.write(obj.city); 
 </script>
</head>
<body>
</body>
</html>
Copy after login

Here we first define a json data and assign it to the json variable, and then JSON.parse() method, convert the json data Convert to js object. Finally, the parsed json data value, which is the js object value, is output to the front desk through the document.write() method.

The parsing result is as shown below:

How to parse json data with js


JSON is usually used to exchange data with the server. When receiving server data, it is usually a string. So we can use the JSON.parse() method to convert the data into a JavaScript object.

Note:

JSON cannot store Date objects. If you need to store a Date object, you need to convert it to a string, and then convert the string to a Date object.

JSON does not allow functions, but you can store functions as strings and later convert the strings to functions.

This article is about the specific method of js parsing json data. It is simple and easy to understand. I hope it will be helpful to friends in need!

The above is the detailed content of How to parse json data with js. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template