JSON是JavaScript Object Notation的縮寫,是一種輕量級(jí)的數(shù)據(jù)交換格式。在Web應(yīng)用中,它經(jīng)常被用來(lái)作為數(shù)據(jù)交換格式,也可以被用來(lái)在JavaScript程序中存儲(chǔ)數(shù)據(jù)。
JSON的語(yǔ)法與JavaScript的語(yǔ)法相似,它由鍵值對(duì)組成,并用大括號(hào){}括起來(lái)。鍵必須是字符串,用引號(hào)括起來(lái),值可以是字符串、數(shù)字、布爾值、數(shù)組、對(duì)象等。以下是一個(gè)JSON的例子:
{ "name": "John Smith", "age": 30, "isMarried": false, "hobbies": ["reading", "traveling"], "address": { "street": "123 Main St", "city": "New York", "state": "NY" } }
在JavaScript程序中,我們可以使用JSON對(duì)象來(lái)解析這個(gè)JSON字符串,并提取出相應(yīng)的數(shù)據(jù)。以下是一個(gè)簡(jiǎn)單的例子:
const jsonString = '{"name": "John Smith","age": 30,"isMarried": false,"hobbies": ["reading", "traveling"],"address": {"street": "123 Main St","city": "New York","state": "NY"}}'; const jsonData = JSON.parse(jsonString); const name = jsonData.name; // John Smith const age = jsonData.age; // 30 const hobbies = jsonData.hobbies; // ["reading", "traveling"] const city = jsonData.address.city; // New York
在這個(gè)例子中,我們先定義了一個(gè)JSON字符串,然后使用JSON.parse()方法將它解析成JSON對(duì)象,再通過(guò)訪問(wèn)JSON對(duì)象的屬性來(lái)提取數(shù)據(jù)。我們可以看到,提取數(shù)據(jù)的方式與訪問(wèn)JavaScript對(duì)象的屬性一樣簡(jiǎn)單。