5月29日 01:08
What are the syntax rules of JSON? Please list and explain them.
Detailed Explanation of JSON Syntax Rules
JSON syntax is based on JavaScript object literal syntax, but there are some strict rules that must be followed:
1. Data Structures
JSON supports two main data structures:
- Object: Consists of key-value pairs, enclosed in curly braces
{} - Array: An ordered list of values, enclosed in square brackets
[]
2. Key-Value Pair Rules
- Keys must be enclosed in double quotes:
"name": "value", single quotes or no quotes are not allowed - Key-value pairs are separated by commas:
"name": "value", "age": 25 - No trailing comma after the last key-value pair: This is an important difference between JSON and JavaScript object literals
3. Value Types
JSON supports the following data types:
- String: Must be enclosed in double quotes, e.g.,
"hello" - Number: Can be an integer or floating-point number, e.g.,
42or3.14 - Boolean:
trueorfalse - Null:
null - Object: Nested JSON objects
- Array: Ordered list of values
4. Special Character Handling
Special characters in strings need to be escaped with a backslash \, such as:
\n: Newline\t: Tab\": Double quote\\: Backslash itself
5. Other Rules
- No comments allowed: Comments cannot be added in JSON
- No functions allowed: Functions cannot be included in JSON
- No undefined support: undefined values cannot be used in JSON
- Case-sensitive:
trueandTRUEare different, only lowercasetrueis valid