在Python中操作JSON数据主要涉及以下步骤:
- 导入模块 :
import json
- 将Python对象转换为JSON字符串 :
data = {
"key1": "value1",
"key2": "value2"
}
json_data = json.dumps(data)
print(json_data)
- 将JSON字符串转换为Python对象 :
json_str = '{"key1": "value1", "key2": "value2"}'
data = json.loads(json_str)
print(data)
- 将Python对象写入JSON文件 :
filename = "data.json"
with open(filename, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=5)
- 从JSON文件读取数据 :
filename = "data.json"
with open(filename, "r", encoding="utf-8") as f:
data = json.load(f)
print(data)
- 检查JSON中是否存在某个键 :
if "key1" in data.keys():
print("Key1 exists in the JSON data.")
以上是Python操作JSON的基本方法。