zoukankan      html  css  js  c++  java
  • JSON转string、JSON转Object

    JSON转Object官方原文:

    地址:http://www.json.org/js.html

    To convert a JSON text into an object, you can use the eval() function. eval() invokes the JavaScript compiler. Since JSON is a proper subset of JavaScript, the compiler will correctly parse the text and produce an object structure. The text must be wrapped in parens to avoid tripping on an ambiguity in JavaScript's syntax.

    var myObject = eval('(' + myJSONtext + ')');

    
    

    第一种方式:

    使用js函数eval();

    testJson=eval(testJson);是错误的转换方式。

    正确的转换方式需要加(): testJson = eval("(" + testJson + ")");

    eval()的速度非常快,但是他可以编译以及执行任何javaScript程序,所以会存在安全问题。在使用eval()。来源必须是值得信赖的。需要使用更安全的json解析器。在服务器不严格的编码在json或者如果不严格验证的输入,就有可能提供无效的json或者载有危险的脚本,在eval()中执行脚本,释放恶意代码。

    js代码:
      function ConvertToJsonForJs() {
                //var testJson = "{ name: '小强', age: 16 }";(支持)
                //var testJson = "{ 'name': '小强', 'age': 16 }";(支持)
                var testJson = '{ "name": "小强", "age": 16 }';
                //testJson=eval(testJson);//错误的转换方式
                testJson = eval("(" + testJson + ")");
                alert(testJson.name);
            }

    第二种方式使用jquery.parseJSON()方法对json的格式要求比较高,必须符合json格式

    jquery.parseJSON()

    js代码:
      function ConvertToJsonForJq() {
                var testJson = '{ "name": "小强", "age": 16 }';
                //不知道
                //'{ name: "小强", age: 16 }' (name 没有使用双引号包裹)
                //"{ 'name': "小强", 'age': 16 }"(name使用单引号)
                testJson = $.parseJSON(testJson);
                alert(testJson.name);
            }
    
    
    


  • 相关阅读:
    MySql不允许对同一张表同时进行查询和更新
    MysSql 显示不了中文、乱码问题
    SpringBoot参数访问
    那些年我看过的好文
    关于远程调试
    算法题
    Spring Boot 注解学习
    linux 设置ssh免密登录
    ORA各种错误
    listener.ora tnsnames.ora
  • 原文地址:https://www.cnblogs.com/webzhuo/p/4236215.html
Copyright © 2011-2022 走看看