一、從JSON方法爬數據
在互聯網上,獲取數據是一項基本而必要的工作。JSON方法可以讓我們輕鬆地採集和解析網頁上的數據。
我們以爬取股票數據為例,使用JavaScript中的fetch函數獲取數據,然後使用json()方法解析返回的JSON字符串。
fetch('https://example.com/stockdata.json')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
上述代碼中,fetch函數用於獲取數據,返回的是一個Promise對象,我們通過then()方法鏈式調用,使用json()方法對返回的響應進行解析。由於json()方法也是返回一個Promise對象,因此也可以繼續使用then()方法對解析後的數據進行操作。如果在請求或解析過程中發生錯誤,可以使用catch()方法處理錯誤。
二、JSON的語法規範
JSON的語法是由一些基本元素組成,包括字符串、數字、布爾值和空值等。
一個簡單的JSON示例:
{
"name": "John Smith",
"age": 30,
"isMarried": true,
"address": {
"street": "Main Street",
"city": "New York",
"state": "NY",
"zip": "10001"
}
}
其中,整個JSON對象需要用一對花括號{}括起來;屬性名和屬性值之間需要用冒號:分隔;不同的屬性之間需要用逗號,分隔。字符串需要用引號" "括起來,可以使用單引號' '代替。數字、布爾值和空值不需要引號括起來。
三、JSON方法JS
JSON方法常用於JavaScript編程中,其中JSON.parse()方法用於將JSON字符串轉換為JavaScript對象,JSON.stringify()方法用於將JavaScript對象轉換為JSON字符串。
例如:
//將JSON字符串轉換為JavaScript對象
const jsonStr = '{"name": "John Smith", "age": 30}';
const jsonObj = JSON.parse(jsonStr);
console.log(jsonObj.name); //"John Smith"
//將JavaScript對象轉換為JSON字符串
const jsonObj = {name: "John Smith", age: 30};
const jsonStr = JSON.stringify(jsonObj);
console.log(jsonStr); //'{"name":"John Smith","age":30}'
四、處理JSON的方法
在處理JSON時,有一些常用的方法可以幫助我們更加有效的操作JSON數據。
1. hasOwnProperty()
hasOwnProperty()方法用於檢查一個對象是否包含特定的屬性,它會返回一個布爾值。
const jsonObj = {name: "John Smith", age: 30};
console.log(jsonObj.hasOwnProperty('name')); //true
console.log(jsonObj.hasOwnProperty('gender')); //false
2. Object.keys()
Object.keys()方法返回一個對象自身屬性的鍵(鍵是以數組形式返回的)。
const jsonObj = {name: "John Smith", age: 30};
const keys = Object.keys(jsonObj);
console.log(keys); //["name", "age"]
3. Object.values()
Object.values()方法返回一個對象自身屬性的值(值是以數組形式返回的)。
const jsonObj = {name: "John Smith", age: 30};
const values = Object.values(jsonObj);
console.log(values); //["John Smith", 30]
4. Object.entries()
Object.entries()方法返回一個對象自身屬性的鍵/值對(鍵值對是以數組形式返回的)。
const jsonObj = {name: "John Smith", age: 30};
const entries = Object.entries(jsonObj);
console.log(entries); //[["name", "John Smith"], ["age", 30]]
五、JSON方法匯總
除了以上幾種常用的方法之外,JSON還有很多實用的方法,如下表所示:
| 方法 | 描述 |
|---|---|
JSON.parse() | 將JSON字符串轉換為JavaScript對象 |
JSON.stringify() | 將JavaScript對象轉換為JSON字符串 |
JSON.parseWithReviver() | 使用自定義函數解析JSON字符串 |
JSON.stringifyWithReplacer() | 使用自定義函數將JavaScript對象轉換為JSON字符串 |
JSON.stringifyWithSpacer() | 將JavaScript對象轉換為帶縮進的JSON字符串 |
六、JSON方法的功能
JSON方法的功能非常廣泛,可以用於數據交換、數據存儲、數據傳輸等多個方面。
1. 數據交換
JSON方法可以方便地實現不同系統之間的數據交換。
//從服務器獲取JSON數據
fetch('https://example.com/data.json')
.then(response => response.json())
.then(data => process(data))
.catch(error => console.error(error));
//將數據上傳到服務器
fetch('https://example.com/save', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(data)
})
.then(response => console.log(response))
.catch(error => console.error(error));
2. 數據存儲
JSON方法可以方便地將數據存儲在本地。
//將數據存儲在localStorage中
const data = {name: "John Smith", age: 30};
localStorage.setItem('data', JSON.stringify(data));
//從localStorage中獲取數據
const dataStr = localStorage.getItem('data');
const data = JSON.parse(dataStr);
console.log(data.name); //"John Smith"
3. 數據傳輸
JSON方法可以方便地在客戶端和服務器之間傳輸數據。
//將數據上傳到服務器
fetch('https://example.com/save', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(data)
})
.then(response => console.log(response))
.catch(error => console.error(error));
//從服務器獲取JSON數據
fetch('https://example.com/data.json')
.then(response => response.json())
.then(data => process(data))
.catch(error => console.error(error));
七、JSON方法返回值
JSON方法的返回值可以是任何類型的值,例如:
const jsonObj = {name: "John Smith", age: 30};
const jsonStr = JSON.stringify(jsonObj);
console.log(jsonStr); //字符串
const jsonArr = ['John', 'Smith', 30];
const jsonObj2 = JSON.parse(jsonArr);
console.log(jsonObj2); //對象
const jsonFunc = function() {console.log('Hello world')};
const jsonStr2 = JSON.stringify(jsonFunc);
console.log(jsonStr2); //undefined
八、JSON方法深拷貝
JSON方法可以實現對象的深拷貝,即拷貝出一個新的完全獨立的對象。
const jsonObj = {name: "John Smith", age: 30, address: {city: "New York", state: "NY"}};
const jsonObj2 = JSON.parse(JSON.stringify(jsonObj));
jsonObj2.address.city = "Los Angeles";
console.log(jsonObj.address.city); //"New York"
console.log(jsonObj2.address.city); //"Los Angeles"
九、JSON方法的缺點
JSON方法也有一些不足之處,其中最明顯的一個問題是性能。
由於JSON方法需要進行字符串化和解析操作,因此在處理大量數據時,性能可能會受到影響。在這種情況下,最好使用其他更高效的數據格式,例如二進制格式。
雖然JSON方法的性能問題確實存在,但在大多數應用程序中,它仍然是一個非常實用和靈活的數據格式。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/157587.html
微信掃一掃
支付寶掃一掃