JavaScript 處理 JSON 數據資料
JavaScript 處理 JSON 數據資料
本文大綱
- 前言
- JSON 語法
- 方法 Method - JSON.parse()
- Parse 例外 Exceptions
- 方法 Method - JSON.stringify()
- 存儲數據 - Storing Data
- Stringify 例外 Exceptions
- JSON 物件字面值 object literal
- JSON 陣列字面值 array literal
- JSON 與服務器之交換數據
- JSON HTML
前言
JSON 示例
這個例子是一個 JSON 字符串:
'{"name":"John", "age":30, "car":null}'
- name
- age
- car
let personName = obj.name;
let personAge = obj.age;
JSON 語法
JSON 語法規則
JSON 語法源自 JavaScript 對象符號語法:
- 數據在 鍵(key)/值(value) 的配對方式中儲存,鍵(key) 必須為文字並且需要 "" 雙引號。
- 數據以 ',' 逗號分隔。
- 大花括號 { }容納物件。
- 方括號 [ ] 保存 array 陣列。
- 在 JSON 中,值(value) 必須是以下數據類型之一:
- string
- number
- object
- array
- boolean
- null
格式 Format
JSON 鍵key
{"name":"John"}
JavaScript 鍵key
{name:"John"}
JSON 值
- a string
- a number
- an object
- an array
- a boolean
- null
JavaScript 值
在 JavaScript 中,值可以是上述所有內容,以及任何其他有效的 JavaScript 表達式,包括:
- a function
- a date
- undefined
JavaScript 物件
person = {name:"John", age:31, city:"New York"};
您可以這樣使用 JavaScript 物件:
person.name; // returns John
也可以這樣使用 :
person[name]; // returns John
數據可以這樣修改:
person.name = "Gilbert";
數據也可以這樣修改:
person["name"] = "Gilbert";
方法 Method - JSON.parse()
JSON.parse() 方法 parse in 會把一個JSON字串轉換成 JavaScript的數值或是物件。另外也可選擇使用reviver函數讓這些數值或是物件在被回傳之前做轉換。
Parsing JSON
範例 javascriptJson-01.html : 使用 JavaScript 函數 JSON.parse() 將文本轉換為 JavaScript 物件。
<html>
<body>
<h2>從 JSON 字符串中,創建JavaScript 物件obj</h2>
<p id="demo"></p>
<script>
const txt = '{"name":"John", "age":30, "city":"New York"}';
const obj = JSON.parse(txt);
document.getElementById("demo").innerHTML = obj.name + ", " + obj.age;
</script>
</body>
</html>
Array as JSON
範例 javascriptJson-02.html : 在從 JSON array 上使用 JSON.parse() 時,該方法將返回一個 JavaScript array,而不是一個 JavaScript 物件 object。
<html>
<body> <h2>解析 JSON Array</h2> <p>以 JSON arry形式寫入的數據將被解析為 JavaScript array。</p> <p id="demo"></p> <script> const text = '[ "Ford", "BMW", "Audi", "Fiat" ]'; const myArr = JSON.parse(text); document.getElementById("demo").innerHTML = myArr[0]; </script> </body>
</html>
Parse 例外 Exceptions
解析日期 Dates
JSON 中不允許使用日期物件。 如果需要包含日期,請將其寫為字符串。 您可以稍後將其轉換回日期物件:
範例 javascriptJson-03.js : 使用JSON.parse() 解析 包含日期的JSON字串,並存為一個 JavaScript 物件 object。
const text = '{"name":"John", "birth":"1986-12-14", "city":"New York"}' const obj = JSON.parse(text) console.log(obj) obj.birth = new Date(obj.birth) console.log(obj)
執行結果
{ name: 'John', birth: '1986-12-14', city: 'New York' }
{ name: 'John', birth: 1986-12-14T00:00:00.000Z, city: 'New York' }
或者,您可以使用 JSON.parse() 函數的第二個參數,稱為 reviver。 reviver 參數是一個在返回值之前檢查每個屬性的函數。
範例 javascriptJson-04.js : 使用 JSON.parse() 函數的第二個參數,稱為 reviver。
const text = '{"name":"John", "birth":"1986-12-14", "city":"New York"}' const obj = JSON.parse(text) console.log(obj) obj.birth = new Date(obj.birth) console.log(obj)
執行結果
{ name: 'John', birth: 1986-12-14T00:00:00.000Z, city: 'New York' }
解析函數 Functions
JSON 中不允許使用函數。 如果需要包含函數,請將其寫為字串。 您可以稍後將其轉換回函數:
const text = '{"name":"John", "age":"function () {return 30;}", "city":"New York"}'; const obj = JSON.parse(text); obj.age = eval("(" + obj.age + ")");
方法 Method - JSON.stringify()
將 JavaScript 物件字串化
假設我們在 JavaScript 中有這個物件:
const obj = {name: "John", age: 30, city: "New York"};
使用 JavaScript 函數 JSON.stringify() 將其轉換為字符串。
const myJSON = JSON.stringify(obj);
字串化 JavaScript 陣列 array
也可以對 JavaScript 陣列 array 進行字串化:
const arr = ["John", "Peter", "Sally", "Jane"];
const myJSON = JSON.stringify(arr);
存儲數據
存儲數據時,數據必須是某種格式,無論您選擇將其存儲在何處,文本始終是合法格式之一。 JSON 使得將 JavaScript 物件存儲為文本成為可能。
範例 javascriptJson-05.js;在 本地存儲 local storage 中存儲數據
const myObj = { name: 'John', age: 31, city: 'New York' } const myJSON = JSON.stringify(myObj) localStorage.setItem('testJSON', myJSON) // Retrieving data: let text = localStorage.getItem('testJSON') let obj = JSON.parse(text)
Stringify 例外 Exceptions
Stringify Dates 日期
在 JSON 中,不允許使用日期物件。 JSON.stringify() 函數將任何日期轉換為字串。
const obj = {name: "John", today: new Date(), city : "New York"}; const myJSON = JSON.stringify(obj);
Stringify Functions 函式
在 JSON 中,函數不允許作為物件值。 JSON.stringify() 函數將從 JavaScript 物件中刪除任何函數物件,包括鍵和值。因此,如果您在運行 JSON.stringify() 函數之前將 函數物件 轉換為字符串,則為可行之方法。
const obj = {name: "John", age: function () {return 30;}, city: "New York"};
obj.age = obj.age.toString();
const myJSON = JSON.stringify(obj);
JSON 物件字面值object literal
這是一個 JSON 字串:
'{"name":"John", "age":30, "car":null}'
在 JSON 字串中有一個 JSON 物件字面值object literal,JSON 物件字面值被花括號 { } 包圍。
{"name":"John", "age":30, "car":null}
將 JSON 物件字面值稱為 “JSON 物件” 是一個常見的錯誤。 JSON 不能是物件。 JSON 是一種字串格式。 當數據為字串格式時,數據僅是 JSON。 當它被轉換成一個 JavaScript 變數時,它就變成了一個 JavaScript 物件。
JavaScript 物件 Objects
您可以從 JSON 物件字面值 創建 JavaScript 物件:
myObj = {"name":"John", "age":30, "car":null};
通常,您通過解析 JSON 字串來創建 JavaScript 物件:
myJSON = '{"name":"John", "age":30, "car":null}'; myObj = JSON.Parse(myJSON);
存取物件
範例 javascriptJson-06.js : 您可以使用點 (.) 表示法存取物件值:
const myJSON = '{"name":"John", "age":30, "car":null}' console.log('myJSON 資料型態是 : ' + typeof myJSON) const myObj = JSON.parse(myJSON) console.log('myObj 資料內容是 : ' + myObj + 'myObj 資料型態 : ' + typeof myObj) myName = myObj.name console.log('myName 資料內容是 : ' + myName)
執行結果
myJSON 資料型態是 : string
myObj 資料內容是 : [object Object]myObj 資料型態 : object
myName 資料內容是 : John
您還可以使用方括號 [ ] 表示法存取物件值:
const myJSON = '{"name":"John", "age":30, "car":null}' const myObj = JSON.parse(myJSON) myName = myObj['name'] console.log(myName)
執行結果
John
迴圈存取物件
範例 javascriptJson-07.js : 您可以使用 for-in 循環遍歷物件屬性。
const myJSON = '{"name":"John", "age":30, "car":null}' const myObj = JSON.parse(myJSON) let text = '' for (const x in myObj) { text += x + ', ' } console.log(text)
執行結果
name, age, car,
範例 javascriptJson-08.js : 在 for-in 循環中,使用括號表示法存取屬性值。
const myJSON = '{"name":"John", "age":30, "car":null}'; const myObj = JSON.parse(myJSON); let text = ""; for (const x in myObj) { text += myObj[x] + ", "; } console.log(text)
執行結果
John, 30, null,
JSON 陣列字面值 array literal
這是一個 JSON 字串:
'["Ford", "BMW", "Fiat"]'
在 JSON 字串中有一個 JSON 陣列字面值 array literal:
["Ford", "BMW", "Fiat"]
JavaScript Array 陣列
myArray = ["Ford", "BMW", "Fiat"];
您可以通過解析 JSON 字串來創建 JavaScript Array 陣列:
myJSON = '["Ford", "BMW", "Fiat"]'; myArray = JSON.Parse(myJSON);
存取陣列值
const myJSON = '["Ford", "BMW", "Fiat"]' const myArray = JSON.parse(myJSON) console.log(myArray[0])
執行結果
Ford
物件中的陣列
物件中可包含陣列
const myJSON = '{"name":"John", "age":30, "cars":["Ford", "BMW", "Fiat"]}' const myObj = JSON.parse(myJSON) console.log(myObj.cars[1])
執行結果
BMW
迴圈遍歷陣列
範例 javascriptJson-09.js : 您可以使用 for in 迴圈遍歷陣列。
const myJSON = '{"name":"John", "age":30, "cars":["Ford", "BMW", "Fiat"]}' const myObj = JSON.parse(myJSON) let text = '' for (let i in myObj.cars) { text += myObj.cars[i] + ', ' } console.log(text)
執行結果
Ford, BMW, Fiat,
範例 javascriptJson-10.js : 或者您可以使用 for 迴圈遍歷陣列。
const myJSON = '{"name":"John", "age":30, "cars":["Ford", "BMW", "Fiat"]}' const myObj = JSON.parse(myJSON) let text = '' for (let i = 0; i < myObj.cars.length; i++) { text += myObj.cars[i] + ', ' } console.log(text)
執行結果
Ford, BMW, Fiat,
JSON 與服務器之交換數據
JSON 的一個常見用途是與 Web 服務器交換數據。 從 Web 服務器接收數據時,數據始終是字串。 用 JSON.parse() 解析數據,數據就變成了一個 JavaScript 物件。
發送數據 Sending Data
如果您將數據存儲在 JavaScript 物件中,您可以將該物件轉換為 JSON,並將其發送到服務器:
const myObj = {name: "John", age: 31, city: "New York"}; const myJSON = JSON.stringify(myObj);
接收數據 Receiving Data
如果您接收 JSON 格式的數據,您可以輕鬆地將其轉換為 JavaScript 物件:
const myJSON = '{"name":"John", "age":31, "city":"New York"}'; const myObj = JSON.parse(myJSON);
來自服務器的 JSON 數據 JSON, From a Server
您可以利用 AJAX request請求 從服務器請求JSON。
只要來自服務器的響應以 JSON 格式編寫,您就可以將字串解析為 JavaScript 物件:
const xmlhttp = new XMLHttpRequest(); xmlhttp.onload = function() { const myObj = JSON.parse(this.responseText); document.getElementById("demo").innerHTML = myObj.name; }; xmlhttp.open("GET", "json_demo.txt"); xmlhttp.send();
JSON陣列形式 Aaary as JSON
在從陣列衍生的 JSON 上使用 JSON.parse() 時,該方法將返回一個 JavaScript 陣列,而不是一個 JavaScript 物件:
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
const myArr = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myArr[0];
}
}
xmlhttp.open("GET", "json_demo_array.txt", true);
xmlhttp.send();
JSON HTML
JSON 可以很容易地轉換為 JavaScript。
JavaScript 可用於在您的網頁中製作 HTML。
HTML Table表格
範例 javascriptJson-12.js : 使用以 JSON 格式接收的數據製作 HTML 表格。
const dbParam = JSON.stringify({ table: 'customers', limit: 20 }) const xmlhttp = new XMLHttpRequest() xmlhttp.onload = function () { const myObj = JSON.parse(this.responseText) let text = "<table border='1'>" for (let x in myObj) { text += '<tr><td>' + myObj[x].name + '</td></tr>' } text += '</table>' document.getElementById('demo').innerHTML = text } xmlhttp.open('POST', 'json_demo_html_table.php') xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded') xmlhttp.send('x=' + dbParam)
動態 HTML 表格
範例 javascriptJson-13.html : 根據下拉式選單的值製作動態 HTML 表格。
<!DOCTYPE html> <html> <body> <h2>Make a table based on the value of a drop down menu.</h2> <select id="myselect" onchange="change_myselect(this.value)"> <option value="">Choose an option:</option> <option value="customers">Customers</option> <option value="products">Products</option> <option value="suppliers">Suppliers</option> </select> <p id="demo"></p> <script> function change_myselect(sel) { const dbParam = JSON.stringify({table:sel,limit:20}); const xmlhttp = new XMLHttpRequest(); xmlhttp.onload = function() { myObj = JSON.parse(this.responseText); text = "<table border='1'>" for (x in myObj) { text += "<tr><td>" + myObj[x].name + "</td></tr>"; } text += "</table>" document.getElementById("demo").innerHTML = text; } xmlhttp.open("POST", "json_demo_html_table.php", true); xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlhttp.send("x=" + dbParam); } </script> </body> </html>
HTML Drop Down List
範例 javascriptJson-13.html : 使用作為 JSON 接收的數據製作 HTML 下拉列表。
<!DOCTYPE html> <html> <body> <h2>Make a drop down list based on JSON data.</h2> <p id="demo"></p> <script> const dbParam = JSON.stringify({table:"customers",limit:20}); const xmlhttp = new XMLHttpRequest(); xmlhttp.onload = function() { const myObj = JSON.parse(this.responseText); let text = "<select>" for (let x in myObj) { text += "<option>" + myObj[x].name; } text += "</select>" document.getElementById("demo").innerHTML = text; } xmlhttp.open("POST", "json_demo_html_table.php"); xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlhttp.send("x=" + dbParam); </script> </body> </html>
參考資料
特色、摘要,Feature、Summary:
關鍵字、標籤,Keyword、Tag:
- JavaScript,Json,Programming-Language,Data-Model,
留言
張貼留言
Aron阿龍,謝謝您的留言互動!