• JSON (JavaScript Object Notation):一种轻量级的数据交换格式,易于人类阅读和编写,同时也易于机器解析和生成。它广泛用于网络数据传输和配置文件
  • JSON的整体是由花括号{}定义的键值对,值包括字符串、数字、布尔值、对象、数组和 null
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
{
  "name": "Alice",
  "age": 30,
  "isStudent": false,
  "fruit": ["apple", "banana", "cherry"],
  "birthday": {
      "year": 2000,
      "month": 12,
      "day": null
  }
}
  • 在python中,可使用json库高效处理json格式:
    • 键值对(对象) → Python字典
    • 布尔值true/false → Python True/False
    • 数组 → Python 列表list
    • null → Python None
1
import json

1. json对象

  • json对象 → Python字典
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# JSON 字符串
json_str = '{"name": "Alice", "age": 30, "isStudent": false}'

# 解析 JSON
data = json.loads(json_str)
data.items()
# dict_items([('name', 'Alice'), ('age', 30), ('isStudent', False)])

data['birth'] = {"year":2000, 'month':12, "day":None}
data['like'] = ['apple', 'banana', 'cherry']
  • **Python字典 → json对象 **
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
json_str = json.dumps(data)
print(json_str)
# {"name": "Alice", "age": 30, "isStudent": false, "birth": {"year": 2000, "month": 12, "day": null}, "like": ["apple", "banana", "cherry"]}

json_str = json.dumps(data, indent=4)
print(json_str)
# {
#     "name": "Alice",
#     "age": 30,
#     "isStudent": false,
#     "birth": {
#         "year": 2000,
#         "month": 12,
#         "day": null
#     },
#     "like": [
#         "apple",
#         "banana",
#         "cherry"
#     ]
# }

2. json文件

  • 保存python字典为json文件
1
2
with open('demo.json', 'w') as file:
    json.dump(data, file, indent=4)
  • 读取json文件为python字典
1
2
with open('demo.json', 'r') as file:
    data = json.load(file)