Home > Article > Web Front-end > JSON code writing specifications
When AJAX implements front-end and back-end data interaction, the data format of JSON is usually used. For JSON, there are strict code specifications. Once there is a problem with the format, the corresponding effect cannot be displayed, and an error is not reported on the console. So what are the specifications for writing JSON.
What is JSON?
In the interaction between the front and backend, messages are usually transmitted to each other, so a language that can be "understood" by both parties is needed. The data format here represents language. JSON is a "language" that can be understood by both the front and backends.
Types of JSON
JSON also has different organizational forms, one is JSON object and the other is JSON array. Therefore, when writing code, you need to follow the basic writing methods of objects and arrays.
1. Array method
[{ "city" : "BeiJing", "num" : 5 }, { "city" : "ShenZhen", "num" : 5 }, { "city" : "XiaMen", "num" : 5 }]
2. Object method
{ "user" : "ZhangSan", "type" : "work", "team" : [{ "city" : "BeiJing", "num" : 3 }, { "city" : "GuangZhou", "num" : 3 }, { "city" : "ShangHai", "num" : 3 }] }
Notes on writing JSON
1. Strings in arrays or objects must use double quotes, single quotes cannot be used
{'user' : ' zhangsan'}//Illegal
{"user": 'zhangsan'}//Illegal
2. The member name of the object must use double quotes
{"user" : "zhangsan"}//Legal
3. There cannot be a comma after the last member of the array or object
[{ "city" : "BeiJing", "num" : 5,//不合法 }, { "city" : "ShenZhen", "num" : 5,//不合法 }]
4. The value of each member of the array or object can be a simple value or a composite value. There are four types of simple values: string, numeric value (must be expressed in decimal), Boolean value and null (NaN, Infinity, -Infinity and undefined will all be converted to null). There are two types of composite values: JSON-formatted objects and JSON-formatted arrays.
{"age" : ox16}//Illegal, the value must be decimal
{"city" : undefined}//Use undefined, it is illegal
1 {"city" : null,
2 "getcity ": function() {
3 console.log("Error usage");
4 }}//You cannot use custom functions or system built-in functions (such as Date()) in JSON
For more articles related to JSON code writing specifications, please pay attention to the PHP Chinese website!