你的位置: 首页>> JS&CSS, 技术天空 >> JavaScript中的 JSON

JavaScript中的 JSON

热度:



* 作者:Douglas Crockford
* 原文网址:http://www.json.org/js.html
* 译者:可爱的猴子

JavaScript这种编程语言首要的目的是为Netscape Navigator提供一种页面脚本语言。它仍被普遍的认为是Java 的一个子集,但事实并非如此。它是一种语法类似c语言并且支持面向对象的Scheme-like语言。JavaScript使用了ECMAScript 语言规范第三版进行了标准化。

JSON是JavaScript面向对象语法的一个子集。由于JSON是JavaScript的一个子集,因此它可清晰的运用于此语言中。

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”

为了将JSON文本转换为对象,可以使用eval()函数。eval()函数调用JavaScript编辑器。由于JSON是JavaScript 的子集,因此编译器将正确的解析文本并产生对象结构。文本必须括在括号中避免产生JavaScript的语法歧义。

var myObject = eval(’(’ + myJSONtext + ‘)’);

eval函数非常快速。它可以编译执行任何JavaScript程序,因此产生了安全性问题。当使用可信任与完善的源代码时才可以使用eval函数。这样可以更安全的使用JSON解析器。使用XMLHttpRequest的web应用,页面之间的通讯只允许同源,因此是可以信任的。但这却不是完善的。如果服务器没有严谨的JSON编码,或者没有严格的输入验证,那么可能传送包括危险脚本的无效JSON文本。eval函数将执行恶意的脚本。

使用JSON解析器可以防止此类事件。JSON解析器只能辨识JSON文本,拒绝所有脚本。提供了本地JSON支持的浏览器的JSON解析器将远快于eval函数。预计未来的ECMAScript标准将支持本地JSON。

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

一个替换函数(reviver function)做为可选参数被最终结果的每一级的键(key)与值(value)调用。 每个值都将被替换函数的值代替。这可以用来将一般的类改变成伪类的实例,或者将日期字符串转变为日期对象。

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 stringifier进行反向操作,可以把JavaScript数据结构转换为JSON文本。JSON不支持循环数据结构,因此应小心不要为JSON stringifier提供循环结构。

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

如果stringify函数发现一个带有toJSON方法的对象,它将执行此方法,并且返回产生的值。这样一个对象就可以决定自己的JSON表现。

stringifier方法可以携带一个可选的字符串数组。这些字符串被用于选择包括在JSON文本中的属性。

stringifier方法可以携带一个可选的替代(replacer)函数。它将在结构中每个值的toJSON方法(如果有的话)后面执行。它将每个键与值做为参数传递,当然对象要包含这个键。返回值将被字符串化。

如果没有提供数组或替代函数,一个用于忽略被集成的属性的可选替代函数将被提供。如果想要所有被继承的属性,可以提供一个简单的替换函数:

var myJSONText = JSON.stringify(myObject, function (key, value) {
return value;
});

对于在JSON中没有表达的值(如函数与undefined)是排除在外的。

不能确定的数量将被替换为null。为了替代其它的值,可以像下面一样使用替换(replacer)函数

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.

随机日志

Tags:

留个脚印

Copyright © 2010 高度PHP All rights reserved.
Designed by Modified by ifanqie. Powered by WordPress.