乐闻世界logo
搜索文章和话题

What are the syntax rules of JSON? Please list and explain them.

2月25日 23:14

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., 42 or 3.14
  • Boolean: true or false
  • 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: true and TRUE are different, only lowercase true is valid
标签:JSON