JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,易于人阅读和编写,同时也易于机器解析和生成。Python 提供了内置的 json
模块来处理 JSON 数据。
{}
。[]
。import json
# JSON 字符串
json_str = '{"name": "Alice", "age": 30, "city": "New York"}'
# 解析 JSON 字符串为 Python 字典
data = json.loads(json_str)
print(data) # 输出: {'name': 'Alice', 'age': 30, 'city': 'New York'}
import json
# Python 字典
data = {
"name": "Bob",
"age": 25,
"city": "Los Angeles"
}
# 将 Python 字典转换为 JSON 字符串
json_str = json.dumps(data)
print(json_str) # 输出: {"name": "Bob", "age": 25, "city": "Los Angeles"}
原因:可能是由于 JSON 字符串格式不正确导致的。
解决方法:
import json
try:
json_str = '{"name": "Alice", "age": 30, "city": "New York"' # 缺少闭合的大括号
data = json.loads(json_str)
except json.JSONDecodeError as e:
print(f"JSON 解析错误: {e}")
原因:JSON 字符串中包含特殊字符(如引号、换行符)可能导致解析失败。
解决方法:
import json
data = {
"description": 'This is a "test" string with\nnew line.'
}
# 使用 ensure_ascii=False 参数来处理特殊字符
json_str = json.dumps(data, ensure_ascii=False)
print(json_str)
希望这些信息对你有所帮助!如果有更多具体问题,请随时提问。
领取专属 10元无门槛券
手把手带您无忧上云