JSON(JavaScript Object Notation)是一種輕量級(jí)的數(shù)據(jù)交換格式,底層傳輸?shù)臋C(jī)制是通過(guò)HTTP協(xié)議發(fā)送的文本,也就是字符串。JSON的數(shù)據(jù)結(jié)構(gòu)由兩種類型組成:鍵值對(duì)和數(shù)組。鍵值對(duì)由一個(gè)字符串類型的key和任意類型的value組成,用冒號(hào)分隔;數(shù)組是一組任意類型的value,用方括號(hào)包裹。
{ "name": "Tom", "age": 18, "gender": "male", "address": { "country": "China", "city": "Shanghai" }, "hobbies": ["reading", "traveling"] }
發(fā)送JSON字符串的時(shí)候,需要注意編碼問(wèn)題。常見(jiàn)的編碼方式有UTF-8、ASCII、GB2312等。在HTTP協(xié)議中,可以設(shè)置Content-Type頭部,指定傳輸?shù)臄?shù)據(jù)格式是JSON,這樣接收方可以自動(dòng)將字符串轉(zhuǎn)為JSON對(duì)象進(jìn)行解析。
POST /api/user HTTP/1.1 Host: example.com Content-Type: application/json;charset=UTF-8 {"name":"Tom","age":18,"gender":"male","address":{"country":"China","city":"Shanghai"},"hobbies":["reading","traveling"]}
在接收方,可以使用JSON.parse()將字符串轉(zhuǎn)為JSON對(duì)象,然后對(duì)對(duì)象進(jìn)行操作。JSON.parse()方法會(huì)自動(dòng)識(shí)別字符串的格式,不需要指定編碼方式。
const jsonData = '{"name":"Tom","age":18,"gender":"male","address":{"country":"China","city":"Shanghai"},"hobbies":["reading","traveling"]}'; const obj = JSON.parse(jsonData); console.log(obj.name); // Tom console.log(obj.address.city); // Shanghai
總的來(lái)說(shuō),JSON底層傳輸是依賴HTTP協(xié)議的,通過(guò)將JSON對(duì)象序列化為字符串,并指定Content-Type頭部,在服務(wù)端和客戶端之間傳輸數(shù)據(jù)。