其他分享
首页 > 其他分享> > js 解析 JSON 数据

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>    

 

标签:json,number,js,alert,JSON,111,phoneNumber,解析
来源: https://www.cnblogs.com/ryanzheng/p/11324555.html