How to access JSON object in JavaScript
By:Roy.LiuLast updated:2019-08-17
Below is a JSON string.
JSON String
"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"
To access the JSON object in JavaScript, parse it with JSON.parse(), and access it via “.” or “[]”.
JavaScript
<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); alert(json["name"]); //mkyong alert(json.name); //mkyong alert(json.address.streetAddress); //88 8nd Street alert(json["address"].city); //New York alert(json.phoneNumber[0].number); //111 111-1111 alert(json.phoneNumber[1].type); //fax alert(json.phoneNumber.number); //undefined </script>
Reference
From:一号门
COMMENTS