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.