【JS從入門到精通】19-JSON
阿新 • • 發佈:2021-08-15
目錄筆記來源:尚矽谷最新版JavaScript基礎全套教程完整版(140集實戰教學,JS從入門到精通)_嗶哩嗶哩_bilibili
JSON
JS 中的物件只有 JS 自己認識,其他的語言都不認識
JSON
就是一個特殊格式的字串,這個字串可以被任意的語言所識別,並且可以轉換為任意語言中的物件,JSON
在開發中主要用來資料的互動
JSON簡介
JavaScript Object Notation,JS 物件表示法
JSON
和 JS 物件的格式一樣,只不過 JSON
JSON分類
物件{}
陣列[]
var obj = { "name": "孫悟空", "age": 1000, "gender": "男" }; console.log(typeof obj); // object var jsonObjStr = '{"name": "孫悟空","age": 1000,"gender": "男"}'; console.log(typeof jsonObjStr); // string var jsonArrStr = '[1,2,3,"hello", true]'; console.log(typeof jsonArrStr); // string
JSON中允許的值
- 字串
- 數值
- 布林值
null
- 物件
- 陣列
// json物件可以包含json陣列
var obj1 = '{"arr":[1,2,3]}';
// json陣列可以包含json物件
var obj2 = '[{"name": "孫悟空","age": 1000,"gender": "男"},{"name": "孫悟空","age": 1000,"gender": "男"}]';
JSON和JS間轉換
在 JS 中,為我們提供了一個工具類,就叫JSON
這個物件可以幫助我們將一個JSON
轉換為 JS 物件,也可以將一個 JS 物件轉換JSON
JSON.parse()
可以將JSON
字串轉換為 JS 中的物件
需要一個JSON
字串作為引數,會將該字串轉換為 JS 物件並返回
var jsonObj = JSON.parse(jsonObjStr);
console.log(typeof jsonObj); // object
console.log(jsonObj); // { name: "孫悟空", age: 1000, gender: "男" }
console.log(jsonObj.name); // 孫悟空
console.log(jsonObj.age); // 1000
console.log(jsonObj.gender); // 男
var jsonArr = JSON.parse(jsonArrStr);
console.log(typeof jsonArr); // object
console.log(jsonArr); // (5) [ 1, 2, 3, "hello", true ]
console.log(jsonArr[0]); // 1
console.log(jsonArr[3]); // hello
console.log(jsonArr[4]); // true
JSON.stringify()
可以將一個 JS 物件轉換為JSON
字串
需要一個 JS 物件作為引數,會返回一個JSON
字串
var obj2 = {
name: "豬八戒",
age: 2000,
gender: "男"
};
var obj2JSONStr = JSON.stringify(obj2);
console.log(typeof obj2JSONStr); // string
console.log(obj2JSONStr); // {"name":"豬八戒","age":2000,"gender":"男"}
JSON
物件在 IE7 及以下的瀏覽器中不支援,所以在這些瀏覽器中呼叫時會報錯
eval()
這個函式可以用來執行一段字串形式的 JS 程式碼,並將執行結果返回
var str = 'alert("hello")';
eval(str);
如果使用eval()
執行的字串中含有{}
,它會將{}
當成是程式碼塊
var jsonObjStr = '{"name": "孫悟空","age": 1000,"gender": "男"}';
eval(jsonObjStr);
如果不希望將其當成程式碼塊解析,則需要在字串前後各加一個()
var jsonObjStr = '{"name": "孫悟空","age": 1000,"gender": "男"}';
var result = eval("(" + jsonObjStr + ")");
console.log(result); // {age: 1000, gender: "男", name: "孫悟空"}
eval()
這個函式的功能很強大,可以直接執行一個字串中的 JS 程式碼
但是在開發中儘量不要使用,首先它的執行效能比較差,然後它還具有安全隱患
相容IE7
如果需要相容 IE7 及以下的JSON
操作,則可以通過引入一個外部的 JS 檔案來處理
<script src="js/json2.js" type="text/javascript" charset="utf-8"></script>
然後在 IE7 瀏覽器中呼叫JSON
相關方法就不會報錯了
console.log(JSON.parse(jsonObjStr)); // {age: 1000, gender: "男", name: "孫悟空"}
一開始介紹JSON
時,說JSON
字串中的屬性名必須加雙引號
如果我就是不加呢?
var jsonObjStr = '{name: "孫悟空","age": 1000,"gender": "男"}';
console.log(JSON.parse(jsonObjStr));
那就是一堆錯誤等著你了