Posted in Javascript onApril 21, 2020
本文实例讲述了js 解析 JSON 数据。分享给大家供大家参考,具体如下:
JSON 数据如下:
{ "name": "mkyong", "age": 30, "address": { "streetAddress": "88 8nd Street", "city": "New York" }, "phoneNumber": [ { "type": "home", "number": "111 111-1111" }, { "type": "fax", "number": "222 222-2222" } ] }
要在JavaScript中访问JSON对象,使用 JSON.parse() 解析它,并通过“.”或“[]”访问。
JS 代码如下:
<script> var data = '{"name": "mkyong","age": 30,"address": {"streetAddress": "88 8nd Street","city": "New York"},"phoneNumber": [{"type": "home","number": "111 111-1111"},{"type": "fax","number": "222 222-2222"}]}'; var json = JSON.parse(data); console.log(json["name"]); //mkyong console.log(json.name); //mkyong console.log(json.address.streetAddress); //88 8nd Street console.log(json["address"].city); //New York console.log(json.phoneNumber[0].number); //111 111-1111 console.log(json.phoneNumber[1].type); //fax console.log(json.phoneNumber.number); //undefined </script>
运行结果:
感兴趣的朋友可以使用在线HTML/CSS/JavaScript代码运行工具:http://tools.3water.com/code/HtmlJsRun测试上述代码运行效果。
js 解析 JSON 数据简单示例
- Author -
Ryan_zheng声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@