zoukankan      html  css  js  c++  java
  • JSON支持什么对象/类型?

    当一个面试官问你: JSON都支持什么对象/类型?你怎么回答?

    也许他的本意是下面这个答案:

    JSON格式支持的数据类型有以下:

    类型描述
    Number 在JavaScript中的双精度浮点格式
    String 双引号的反斜杠转义的Unicode
    Boolean true 或 false
    Array 值的有序序列
    Value 它可以是一个字符串,一个数字,真的还是假(true/false),空(null )等
    Object 无序集合键值对
    Whitespace 可以使用任何一对中的令牌
    null empty
     

    但我还真不这么认为,我认为支持任意对象类型,只要是接收容器里面存在的就可以。

    可以使用下面的示例来证明:

     

    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
    <meta charset="utf-8">
    <script src="../resources/js/jquery-1.8.3.min.js"></script>
    </head>
    <body></body>
    </html>
    <script>
        function ClassA(sColor) {
            this.color = sColor;
            this.sayColor = function() {
                alert(this.color);
            };
        }
    
        function strToJson(str) {
            var json = eval('(' + str + ')');
            return json;
        }
    
        jQuery.ajax({
            type : "get",
            cache : false,
            dataType : "text",
            url : "simple.json",
            success : function(data) {
                alert(data);
                var _json = strToJson(data);
                _json.testcolor.sayColor(); // 这里是我们想看的效果
            },
            error : function() {
                alert('对不起,服务请求异常!');
            }
        }); 
    </script>

     

    simple.json文件内容:

     

    {
        "retCode": "0000",
        "retMsg": "Success",
        "testcolor": new ClassA("red"),
        "retList": {
            "le1": {
                "price": "4800000",
                "commId": "56761"
            },
            "le2": {
                "price": "4800000",
                "commId": "56761"
            }
        }
    }

     

    注意上面代码里面的 dataType : "text"

    因为Jquery源码里面是用下面的方式转换的,我们需要更加原始的方式,所以我替换成了自定义的strToJson(str)

    Jquery源码:

        // Evaluates a script in a global context
        // Workarounds based on findings by Jim Driscoll
        // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
        globalEval: function( data ) {
            if ( data && core_rnotwhite.test( data ) ) {
                // We use execScript on Internet Explorer
                // We use an anonymous function so that context is window
                // rather than jQuery in Firefox
                ( window.execScript || function( data ) {
                    window[ "eval" ].call( window, data );
                } )( data );
            }
        },

     

    其实JSON就是字符串,需要前端进行eval转换,所以不能简单的说json支持什么对象,或者支持什么数据类型。

    注意提问方式,需要更加严谨提出我们想要提问的问题。

     

     

  • 相关阅读:
    django+xadmin在线教育平台慕学网(一)
    django.db.migrations.exceptions.InconsistentMigrationHistory django报错
    mac系统 MySQL 8.0.11版本,安装成功,使用Navicat连接失败
    MySQL-表操作
    MySQL的数据类型
    存储引擎
    库操作
    MySQL学习目录
    初识MySQL数据库
    静态方法和类方法
  • 原文地址:https://www.cnblogs.com/zhoulf/p/4568234.html
Copyright © 2011-2022 走看看