JSON簡介
JSON(JavaScript Object Notation)即JavaScript對象表示法,一種輕量級,通用的文本數據格式。
JSON語法支持對象(Object),數組(Array),字符串,數字(int/float)以及true/false和null。
JSON擁有嚴格的格式,主要格式如下:
- 只能用雙引號,不能用單引號
- 元素之間用逗號隔開,最后一個元素不能有逗號
- 不支持注釋
- 中文等特殊字符傳輸時應確保轉為ASCII碼(\uXXX格式)
- 支持多層嵌套Object或Array
示例格式,文件demo.json:
{
"name": "Cactus",
"age": 18,
"skills": ["Python", "Java", "Go", "NodeJS"],
"has_blog": true,
"gf": null
}
JSON與Python數據類型的對應關系
JSON和Python中的字典等類型一一對應:
JSON | Python |
---|---|
Object | 字典 |
Array | 列表 |
字符串 | 字符串 |
數字 | 數字(int/float) |
true/false | True/False |
null | Null |
注意:在Python中, JSON一般指符合JSON語法格式的字符串,實際上是一個字符串,單行或者多行。
JSON字符串與Python字典的相互轉換
為什么要相互轉換,JSON是字符串,方便存儲傳輸,不方便提取值;字典是內存中的數據結構,取值方便,不方便傳輸和存儲
使用Python自帶的json包可以完成字典與JSON字符串的相互轉換
- json.dumps(字典):將字典轉為JSON字符串
- json.loads(JSON字符串):將JSON字符串轉為字典,如果字符串不是合法的JSON格式,會報JSONDecodeError
示例1,字典轉JSON字符串
import json
dict_var = {
'name': 'Cactus',
'age': 18,
'skills': ['Python', 'Java', 'Go', 'NodeJS'],
'has_blog': True,
'gf': None
}
print(json.dumps(dict_var))
print(json.dumps(dict_var, indent=2,sort_keys=True, ensure_ascii=False))
json.dumps()支持參數,indent為多行縮進空格數,sort_keys為是否按鍵排序,ensure_ascii=False為不確保ascii,及不將中文等特殊字符轉為\uXXX等
顯示結果:
{"name": "Cactus", "age": 18, "skills": ["Python", "Java", "Go", "NodeJS"], "has_blog": true, "gf": null}
{
"age": 18,
"gf": null,
"has_blog": true,
"name": "Cactus",
"skills": [
"Python",
"Java",
"Go",
"NodeJS"
]
}
示例2,JSON字符串->字典
import json
json_str = '''{
"name": "Cactus",
"age": 18,
"skills": ["Python", "Java", "Go", "NodeJS"],
"has_blog": true,
"gf": null
}'''
print(json.loads(json_str))
顯示結果:
{'name': 'Cactus', 'age': 18, 'skills': ['Python', 'Java', 'Go', 'NodeJS'], 'has_blog': True, 'gf': None}
JSON文件與字典的相互轉換
另外也可以直接將字典保存為JSON文件或從JSON文件轉為字典
- json.dump(字典, f):將字典轉為JSON文件(句柄)
- json.loads(f):將打開的JSON文件句柄轉為字典
示例3:字典->JSON文件
import json
dict_var = {
'name': 'Cactus',
'age': 18,
'skills': ['Python', 'Java', 'Go', 'NodeJS'],
'has_blog': True,
'gf': None
}
with open("demo2.json", "w", encoding='utf-8') as f:
# json.dump(dict_var, f) # 寫為一行
json.dump(dict_var, f,indent=2,sort_keys=True, ensure_ascii=False) # 寫為多行
文件demo2.json結果:
{
"age": 18,
"gf": null,
"has_blog": true,
"name": "Cactus",
"skills": [
"Python",
"Java",
"Go",
"NodeJS"
]
}
示例4: JSON文件->字典
import json
with open("demo2.json", encoding="utf-8") as f:
data = json.load(f)
pritn(data)
顯示結果:
{'age': 18, 'gf': None, 'has_blog': True, 'name': 'Cactus', 'skills': ['Python', 'Java', 'Go', 'NodeJS']}
注意:字典轉為JSON時,只支持嵌套字典、列表、字符串、數字、True/False/None等,不支持日期對象以及Python的其他對象
需要進行相互轉換的可以參考:https://python3-cookbook.readthedocs.io/zh_CN/latest/c06/p02_read-write_json_data.html
解析復雜嵌套JSON格式,請使用JSONPath