• 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);
            }
    
    
    


  • 相关阅读:
    Netty和Akka有什么不同?
    GitHub & Bitbucket & GitLab & Coding 的对比分析
    Log4j和Log4j2的区别
    Spring中MultipartHttpServletRequest实现文件上传 生成缩略图
    JSP显示-下拉框
    jsp页面 date转化成string
    tomcat直接访问
    web项目中各种路径的获取HttpServletRequest
    遍历Map的四种方法
    mybatis There is no getter for property named 'xx' in 'class java.lang.String
  • 原文地址:https://www.cnblogs.com/webzhuo/p/4236215.html
Copyright © 2020-2023  润新知