zoukankan      html  css  js  c++  java
  • json字符串与json对象转换

    从网上找的几种常用的转换方法,测试结果如下:

    1、json字符串——>json对象

     1 /* test 1 */
     2 var str = '{"a":1,"b":2}';
     3 
     4 var s1 = JSON.parse(str); //OK 
     5 console.log(s1); //{ a: 1, b: 2 }
     6 
     7 var s2 =  eval('(' + str + ')'); //OK
     8 console.log(s2); //{ a: 1, b: 2 }
     9 
    10 var s3 = str.parseJSON(); //TypeError: str.parseJSON is not a function
    11 console.log(s3);
    12 
    13 
    14 /* test 2 */
    15 var str1 = '{a:1,b:2}';
    16 
    17 var s1 = JSON.parse(str1); //SyntaxError: Unexpected token a
    18 console.log(s1);
    19 
    20 var s2 =  eval('(' + str1 + ')'); //OK
    21 console.log(s2); //{ a: 1, b: 2 }
    22 
    23 var s3 = str1.parseJSON(); //TypeError: str.parseJSON is not a function
    24 console.log(s3);
    JSON.parse(str)可用,使用时要注意字符串格式
    eval('(' + str + ')')可用

    2、json对象——>json字符串

    1 var str = { a: 1, b: 2 };
    2 
    3 var s1 = str.toJSONString(); // TypeError: str.toJSONString is not a function
    4 console.log(s1); 
    5 
    6 var s2 =  JSON.stringify(str);  //OK
    7 console.log(typeof s2); //string
    8 console.log(s2); //{"a":1,"b":2}
    JSON.stringify(str)可用
  • 相关阅读:
    知识体系总结
    计算机基础总结
    Redis总结
    Mysql总结
    JAVA基础总结
    有锁编程
    CAS
    读写自旋锁
    org.apache.log4j.Logger详解
    web.xml 中的listener、 filter、servlet 加载顺序及其详解
  • 原文地址:https://www.cnblogs.com/suiyueshentou/p/6186180.html
Copyright © 2011-2022 走看看