[译]JavaScript中的JSON

 

JavaScript中的JSON

 

JavaScript是为网景浏览器做页面脚本语言而实现的一种编程语言。它现在还被很多人误解是java的子集。它是一种具有类C语法和弱对象的模式语言。JavaScript完全遵守ECMAScript语言说明书第三版。

JSON是JavaScript对象文字记号的子集。由于JSON是JavaSript的子集,所以在JavaScript里,可以方便的应该JSON。

var myJSONObject = {"bindings": [

        {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"},

        {"ircEvent": "PRIVMSG", "method": "deleteURI", "regex": "^delete.*"},

        {"ircEvent": "PRIVMSG", "method": "randomURI", "regex": "^random.*"}

    ]

};

在这个例子里面,创建一个单独的成员——“bindings”,这个成员里包含一个有三个对象——“ircEvent”, “method”和“regex”的对象数组。

数据可以用逗号(,)或者下标符,例:

myJSONObject.bindings[0].method    // "newURI"

您可心用eval()把JSON中的数据转化为对象。 Eval()可以调用javascript编译器。由于JSON是JavaScript的子集,编译器可以正确的把文本转化为对象结构。这个字段必须是包在父的语法中的,避免在JavaScript的语法下产生二意性。

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

       这具eval函数运行非常快,但它能编译和运行任何JavaScript程序,因此有一定的安全隐患。当源代码是可信任并且合适的时候,eval的用法是完全可以的。E用JSON剖析器更加安全。在XMLHttpRequest的网页应用程序中,只有相同的源程序提供页面被允许,因此它是可信的。但它也有不可以的时候:如果服务器在JSON编码上不严密或者它没有全部证实它的所有输入的话,它可能发送带有危险脚本的不合法JSON文本。而eval函数能运行这个脚本,释放出危险。

       用JSON解析器就能防止这种事情,JSON解析器只认JSON内容,不认作保脚本。在支持JSON的浏览器中,JSON解析器比eval快多了,期望在ECMAScript标准的下一个版本中会包含对本地JSON的支持。

var myObject = JSON.parse(myJSONtext, reviver);

可选参数reviver是一个最后在结果中myJSONtext所有级别的键值所调用的函数。每个值都可以被reviver的结果替换。这个可以用来把类对象转化为虚类,或者是把日期字符串转化为日期类型。

myData = JSON.parse(text, function (key, value) {
    var type;
    if (value && typeof value === 'object') {
        type = value.type;
        if (typeof type === 'string' && typeof window[type] === 'function') {
            return new (window[type])(value);
        }
    }
    return value;
});

       一个JSON字符串识别器是编译器的反作用器,它可以把JavaScript数据结构转化为JSON文本。JSON不支持环型结构的数据,因此在应用JSON字符串识别器时要小心环形结构。

var myJSONText = JSON.stringify(myObject, replacer);

       如果在方法stringify中找到一个包含toJSON方法的对象,就会调用这个方法,并把返回值进行字符串转化。它允许让一个对象来决定它所拥有的JSON表现。

    这个字符串转换的方法可以是一个可行的字符串数组。这些字符串就被用来包含在JSON文本中的属性。

       这个字符串转换的方法可有一个替换的函数。如果有toJSON方法的话,它将在这个方法后后对这个结构中的每一个值调用一次。它将把每一个键值作为一个参数传进来,并将对象和键绑定。这个返回值将被字符转换。

       像函数或undefined之类没有表现的值不在JSON之列。

function replacer(key, value) {
    if (typeof value === 'number' && !isFinite(value)) {
        return String(value);
    }
    return value;
}

 

 

 

 

 

 

JavaScript is a general purpose programming language that was introduced as the page scripting language for Netscape Navigator. It is still widely believed to be a subset of Java, but it is not. It is a Scheme-like language with C-like syntax and soft objects. JavaScript was standardized in the ECMAScript Language Specification, Third Edition.

JSON is a subset of the object literal notation of JavaScript. Since JSON is a subset of JavaScript, it can be used in the language with no muss or fuss.

var myJSONObject = {"bindings": [
        {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"},
        {"ircEvent": "PRIVMSG", "method": "deleteURI", "regex": "^delete.*"},
        {"ircEvent": "PRIVMSG", "method": "randomURI", "regex": "^random.*"}
    ]
};

In this example, an object is created containing a single member "bindings", which contains an array containing three objects, each containing "ircEvent", "method", and "regex" members.

Members can be retrieved using dot or subscript operators.

myJSONObject.bindings[0].method    // "newURI"

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 + ')');

The eval function is very fast. However, it can compile and execute any JavaScript program, so there can be security issues. The use of eval is indicated when the source is trusted and competent. It is much safer to use a JSON parser. In web applications over XMLHttpRequest, communication is permitted only to the same origin that provide that page, so it is trusted. But it might not be competent. If the server is not rigorous in its JSON encoding, or if it does not scrupulously validate all of its inputs, then it could deliver invalid JSON text that could be carrying dangerous script. The eval function would execute the script, unleashing its malice.

To defend against this, a JSON parser should be used. A JSON parser will recognize only JSON text, rejecting all scripts. In browsers that provide native JSON support, JSON parsers are also much faster than eval. It is expected that native JSON support will be included in the next ECMAScript standard.

var myObject = JSON.parse(myJSONtext, reviver);

The optional reviver parameter is a function that will be called for every key and value at every level of the final result. Each value will be replaced by the result of the reviver function. This can be used to reform generic objects into instances of pseudoclasses, or to transform date strings into Date objects.

myData = JSON.parse(text, function (key, value) {
    var type;
    if (value && typeof value === 'object') {
        type = value.type;
        if (typeof type === 'string' && typeof window[type] === 'function') {
            return new (window[type])(value);
        }
    }
    return value;
});

A JSON stringifier goes in the opposite direction, converting JavaScript data structures into JSON text. JSON does not support cyclic data structures, so be careful to not give cyclical structures to the JSON stringifier.

var myJSONText = JSON.stringify(myObject, replacer);

If the stringify method sees an object that contains a toJSON method, it calls that method, and stringifies the value returned. This allows an object to determine its own JSON representation.

The stringifier method can take an optional array of strings. These strings are used to select the properties that will be included in the JSON text.

The stringifier method can take an optional replacer function. It will be called after the toJSON method (if there is one) on each of the values in the structure. It will be passed each key and value as parameters, and this will be bound to object holding the key. The value returned will be stringified.

Values that do not have a representation in JSON (such as functions and undefined) are excluded.

Nonfinite numbers are replaced with null. To substitute other values, you could use a replacer function like this:

function replacer(key, value) {
    if (typeof value === 'number' && !isFinite(value)) {
        return String(value);
    }
    return value;
}

Giving a corresponding reviver to JSON.parse can undo that.

The open source code of a JSON parser and JSON stringifier is available. When minified it is less than 2.5K.

 

英文原文地址 :

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

 

 

你可能感兴趣的:(JavaScript)