Javascript中的JSON

2018-06-23  本文已影响0人  临渊如峙

1、创建和访问

<script type="text/javascript">
     //JSON:JavaScript Object Notation
     var counterArray={
           A:3,
           B:4
     };
     counterArray["C"]=1;
     console.info(counterArray)
     //JSON访问数据的方式:[]或.
     console.info(counterArray["A"])
     console.info(counterArray.B)
     //JSON数组的长度
     console.info(Object.keys(counterArray).length);
</script>

2、JSON格式字符串转为JSON

<script type="text/javascript">
    var jsonstr = "{'name':'mike','age':4}"
    alert(jsonstr)
    alert(typeof jsonstr)

    //将JSON字符串转为JSON--方式一
    var json = eval('('+jsonstr+')')
    alert(json)
    alert(typeof json)

    //将JSON字符串转为JSON--方式二
    var json = JSON.parse(jsonstr)
    alert(json)
    alert(typeof json)
</script>
上一篇 下一篇

猜你喜欢

热点阅读