SON (JavaScript Object Notation)一種簡單的資料格式,比xml更輕巧。 JSON 是 JavaScript 原生格式,這意味著在 JavaScript 中處理 JSON 資料不需要任何特殊的 API 或工具包。
JSON的規則很簡單: 對象是一個無序的“‘名稱/值’對”集合。一個對象以“{”(左括弧)開始,“}”(右括弧)結束。每個“名稱”後跟一個“:”(冒號);“‘名稱/值’ 對”之間使用“,”(逗號)分隔。具體細節參考http://www.json.org/json-zh.html
舉個簡單的例子:
js 代碼
- function showJSON() {
- var user =
- {
- "username":"andy",
- "age":20,
- "info": { "tel": "123456", "cellphone": "98765"},
- "address":
- [
- {"city":"beijing","postcode":"222333"},
- {"city":"newyork","postcode":"555666"}
- ]
- }
-
- alert(user.username);
- alert(user.age);
- alert(user.info.cellphone);
- alert(user.address[0].city);
- alert(user.address[0].postcode);
- }
這表示一個user對象,擁有username, age, info, address 等屬性。
同樣也可以用JSON來簡單的修改資料,修改上面的例子
js 代碼
- function showJSON() {
- var user =
- {
- "username":"andy",
- "age":20,
- "info": { "tel": "123456", "cellphone": "98765"},
- "address":
- [
- {"city":"beijing","postcode":"222333"},
- {"city":"newyork","postcode":"555666"}
- ]
- }
-
- alert(user.username);
- alert(user.age);
- alert(user.info.cellphone);
- alert(user.address[0].city);
- alert(user.address[0].postcode);
-
- user.username = "Tom";
- alert(user.username);
- }
JSON提供了json.js包,下載http://www.json.org/json.js 後,將其引入然後就可以簡單的使用object.toJSONString()轉換成JSON資料。
js 代碼
- function showCar() {
- var carr = new Car("Dodge", "Coronet R/T", 1968, "yellow");
- alert(carr.toJSONString());
- }
-
- function Car(make, model, year, color) {
- this.make = make;
- this.model = model;
- this.year = year;
- this.color = color;
- }
可以使用eval來轉換JSON字元到Object
js 代碼
- function myEval() {
- var str = '{ "name": "Violet", "occupation": "character" }';
- var obj = eval('(' + str + ')');
- alert(obj.toJSONString());
- }
或者使用parseJSON()方法
js 代碼
- function myEval() {
- var str = '{ "name": "Violet", "occupation": "character" }';
- var obj = str.parseJSON();
- alert(obj.toJSONString());
- }