json 字符串 对象 互转

json对象,json字符串,不注意的话,很容易忽视混淆。例举几个容易混的情况

1,php将变量放到input框中,通过js去读取出来的是json字符串,要想使用就要将json字段串转成json对象

2,ajax返回json数据,如果请求没有设置dataType为json,这个时候得到也是json字符串

3,通过js改变input的value值,如果直接json对象,赋值的话,用开发者工具看到的值会是这样的,[Object Object]

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title>Document</title>
    <script type="text/javascript" src="2.1.js"></script>
</head>
<body>
    <script type="text/javascript">
     // alert("aaa");
     var aa = '{"test":1,"test1":2}';  
     var bb = {"test":1,"test1":2};  
     // alert(aa);
     // alert(bb.test);
     //  其中 aa,是json字符串; bb,是json对象
     console.log(aa);
     console.log(bb);
     /**
     {"test":1,"test1":2}
     a.php (第 16 行)
     Object { test=1,  test1=2}
     **/

     // json字符串转json对象
     var obj_a = eval('(' + aa + ')');     //方法1 
     console.log(obj_a);
     var obj_b = JSON.parse(aa);         //方法2  
     console.log(obj_b);

     // json对象转json字符串
     var last=JSON.stringify(bb); 
     console.info(last);
     console.log(last);

    </script>
</body>
</html>
原文地址:https://www.cnblogs.com/wuheng1991/p/5290752.html