JSON与字典的区别及示例

时间:2025-05-08 07:17:48

JSON(JavaScript Object Notation)和 Python 字典(dict)在语法上相似,但本质不同。以下是具体区别和示例:


目录

      • 1. **本质区别**
      • 2. **语法差异**
        • JSON 示例
        • Python 字典示例
      • 3. **转换方法**
        • 字典 → JSON(序列化)
        • JSON → 字典(反序列化)
      • 4. **常见错误**
        • 错误 JSON(Python 字典合法但 JSON 不合法)
        • 错误字典(JSON 合法但 Python 不合法)
      • 5. **应用场景**
      • 总结

1. 本质区别

  • JSON:一种轻量级数据交换格式(字符串形式),独立于编程语言。
  • 字典:Python 中的数据结构(内存对象),可直接操作。

2. 语法差异

JSON 示例
{
  "name": "Alice",
  "age": 30,
  "is_student": false,
  "hobbies": ["reading", "music"],
  "address": {
    "city": "Beijing",
    "postcode": null
  }
}
  • 键必须用双引号
  • 值类型有限:字符串、数字、布尔值(true/false)、数组、对象、null
  • 末尾不能有逗号(如 "postcode": null, 会报错)。
Python 字典示例
person = {
    'name': 'Alice',
    "age": 30,
    'is_student': False,
    'hobbies': ['reading', 'music'],
    'address': {
        'city': 'Beijing',
        'postcode': None
    }
}
  • 键可用单引号、双引号,甚至无引号(若符合变量命名规则,如 name)。
  • 值可以是任意 Python 对象(如函数、类实例)。
  • 布尔值为 True/Falsenull 对应 None
  • 允许末尾逗号(如 'postcode': None, 合法)。

3. 转换方法

字典 → JSON(序列化)
import json

person_dict = {
    'name': 'Bob',
    'age': 25,
    'is_student': True
}
json_str = json.dumps(person_dict)
print(json_str)  # {"name": "Bob", "age": 25, "is_student": true}
JSON → 字典(反序列化)
json_data = '{"name": "Bob", "age": 25, "is_student": true}'
person_dict = json.loads(json_data)
print(person_dict)  # {'name': 'Bob', 'age': 25, 'is_student': True}

4. 常见错误

错误 JSON(Python 字典合法但 JSON 不合法)
{
  'name': 'Alice',  // JSON 必须用双引号
  "age": 30,
  "is_student": False  // JSON 布尔值应为 false(小写)
}
错误字典(JSON 合法但 Python 不合法)
invalid_dict = {
    name: "Alice",  # 键未加引号(除非 name 是变量)
    "age": 30,
    "is_student": true  # Python 布尔值为 True(首字母大写)
}

5. 应用场景

  • JSON:存储、传输数据(如 API 响应、配置文件)。
  • 字典:程序内部处理数据(如临时存储、计算)。

总结

特性 JSON Python 字典
本质 字符串(数据格式) 内存对象(数据结构)
引号 键必须用双引号 单引号/双引号/无引号
布尔值 true/false True/False
空值 null None
数据交换 支持跨语言 仅限 Python 内部使用

通过语法规则和转换工具(如 json 模块)可明确区分二者。