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);
            
    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>    

 

posted @ 2019-08-08 23:40  Ryan_zheng  阅读(11647)  评论(0编辑  收藏  举报