当前位置:编程学习 > JS >>

JavaScript json使用方法

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

文本生成json对象,必须在外面加一对括号。

因为JSON 是 网页特效 的一个子集,所以,在javascript 中使用JSON是非常简单的。
   
   
js 代码
 

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

在上面的例子中,我们创建了只包含一个成员 "bindings" 的一个对象,bindings 则包含了一个由3个对象组成的数组。这3个对象都包含3个成员:"ircEvent", "method","regex"。

在javascript 中, 成员可以通过“点号”来获取。
比如:

js 代码

myJSONObject.bindings[0].method  

通过eval() 函数可以将JSON字符串转化为对象。

js 代码

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

eval 函数非常快,但是它可以编译任何 javascirpt 代码,这样的话就可能产生安全的问题。eval 的使用是基于传入的代码参数是可靠的假设的,有一些情况下,可能客户端是不可信任的。

如果基于安全的考虑的话,最好是使用一个 JSON 解析器。 一个 JSON 解析器将只接受 JSON 文本。所以是更安全的。

js 代码
 

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

可选的 filter 参数将遍历每一个value key 值对, 并进行相关的处理。如:


js 代码

myData = JSON.parse(text, function (key, value) {       

return key.indexOf('date') >= 0 ? new Date(value) : value;    }); 

stringifier 函数的作用跟 parse 相反, 用来将一个js对象转换为 JSON 文本。

js 代码
var myJSONText = JSON.stringifier(myObject);


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

这是国外网站

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 ps教程eudoclasses, 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.

补充:网页制作,js教程 
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,