JSON(JavaScript Object Notation)是一種輕量級的數(shù)據(jù)交換格式,通常用于將JavaScript對象序列化為字符串,以便于傳輸和存儲。JSON的格式非常簡單,但也有一些約定和設(shè)置可供選擇。
//以下是一些JSON的格式設(shè)置示例: //設(shè)置縮進(jìn):使用tab時(shí),可以設(shè)置為\t,使用空格時(shí)可以設(shè)置為2、4、8等 var json = { "name": "張三", "age": 20, "skills": ["Java", "JavaScript", "C++"] }; console.log(JSON.stringify(json, null, "\t")); //輸出結(jié)果: { "name": "張三", "age": 20, "skills": [ "Java", "JavaScript", "C++" ] } //去除空格和換行符: var json = { "name": "張三", "age": 20, "skills": ["Java", "JavaScript", "C++"] }; console.log(JSON.stringify(json).replace(/\s/g, "")); //輸出結(jié)果:{"name":"張三","age":20,"skills":["Java","JavaScript","C++"]} //輸出unicode編碼 var json = { "name": "張三", "age": 20, "skills": ["Java", "JavaScript", "C++"] }; console.log(JSON.stringify(json).replace(/[^\u0000-\u007f]/g, function (x) { return "\\u" + x.charCodeAt(0).toString(16); })); //輸出結(jié)果:{"name":"\u5f20\u4e09","age":20,"skills":["Java","JavaScript","C++"]}
這些設(shè)置可以使JSON格式更加與人類友好,也可以使JSON更容易閱讀和解析。