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代码运行工具:测试上述代码运行效果。
PS:关于json操作,这里再为大家推荐几款比较实用的json在线工具供大家参考使用:
更多关于JavaScript相关内容可查看本站专题:《JavaScript中json操作技巧总结》、《JavaScript查找算法技巧总结》、《JavaScript错误与调试技巧总结》、《JavaScript数据结构与算法技巧总结》、《JavaScript遍历算法与技巧总结》及《JavaScript数学运算用法总结》