使用函数 json.dumps()、loads() 、json.dump()、json.load() 。
1 json.dumps() 将python对象编码成Json字符串
import json
data = {
'name':'Alice',
'age':25,
'gender':'F',
'city':'北京'
}
# 1 json.dumps() 将python对象编码成Json字符串
print(type(data))
json_str = json.dumps(data)
print(type(json_str), json_str)
# ensure_ascii=True:默认输出ASCLL码,如果把这个该成False,就可以输出中文。
json_str = json.dumps(data, ensure_ascii=False)
print(type(json_str), json_str)
'''
<class 'dict'>
<class 'str'> {"name": "Alice", "age": 25, "gender": "F", "city": "\u5317\u4eac"}
<class 'str'> {"name": "Alice", "age": 25, "gender": "F", "city": "北京"}
'''
2 json.loads() 将Json字符串解码成python对象
import json
# 2 json.loads() 将Json字符串解码成python对象
json_str = '{"name": "Alice", "age": 25, "gender": "F", "city": "北京"}'
data = json.loads(json_str)
print(type(data), data)
'''
<class 'dict'> {'name': 'Alice', 'age': 25, 'gender': 'F', 'city': '北京'}
'''
3 json.dump() 将python中的对象转化成json储存到文件中
import json
data = {
'name':'Alice',
'age':25,
'gender':'F',
'city':'北京'
}
# 3 json.dump() 将python中的对象转化成json储存到文件中
with open('example.json', 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False)
# example.json
'''
{"name": "Alice", "age": 25, "gender": "F", "city": "北京"}
'''
4 json.load() 将文件中的json的格式转化成python对象提取出来
import json
# example.json
'''
{"name": "Alice", "age": 25, "gender": "F", "city": "北京"}
'''
# 4 json.load() 将文件中的json的格式转化成python对象提取出来
with open('example.json', 'r', encoding='utf-8') as f:
data = json.load(f)
print(type(data), data)
'''
<class 'dict'> {'name': 'Alice', 'age': 25, 'gender': 'F', 'city': '北京'}
'''
5 判断字符串是否为 Json 格式
import json
def is_json(string):
try:
json.JSONDecoder().raw_decode(string)
return True
except json.JSONDecodeError:
return False
# 5 判断字符串是否为 Json 格式
json_str = '{"name": "Alice", "age": 25, "gender": "F", "city": "北京"}'
print(is_json(json_str))
'''
True
'''
6 异常: json.decoder.JSONDecodeError: Extra data: line 1 column 52 (char 51)
import json
# 判断是否为正常 json
def is_json(string):
try:
json.JSONDecoder().raw_decode(string)
return True
except json.JSONDecodeError:
return False
# 错误的 json 对象,有两个, 判断类型是 True, 但 loads 出错了
json_str = '{"name":"Alice","age":25,"gender":"F","city":"北京"}{"name":"Alice","age":25,"gender":"F","city":"北京"}'
print(is_json(json_str))
try:
data = json.loads(json_str)
except json.decoder.JSONDecodeError as e:
print(f"解析错误: {e}")
'''
True
解析错误: Extra data: line 1 column 51 (char 50)
'''
参考:
python的JSON用法——dumps的各种参数用法(详细)_jsondump用法-CSDN博客
https://blog.csdn.net/qq_46293423/article/details/105785007
json.dump()与json_dumps()区别_json.dumps-CSDN博客
https://blog.csdn.net/lizhixin705/article/details/82344209
Python json.dumps()函数使用解析 | w3cschool笔记
https://www.w3cschool.cn/article/30808038.html
python 判断数据格式是不是json 原创
https://blog.51cto.com/u_16175454/9799422