作者:Gakki
JSON 是一种轻量级得到数据交换格式,易于人阅读和编写。
01 函数的描述
函数 | 描述 |
---|---|
json.load | 从文件中读取json字符串 |
json.dump | 将json格式字符串写到文件中 |
json.loads | 将已编码的 JSON 字符串解码为 Python 对象 |
json.dumps | 将 Python 对象编码成 JSON 字符串 |
02 实例
- json.load():从文件中读取json字符串
import json
with open('text.json','r',encoding='utf-8') as f :
print(json.load(f))
输出结果:
{'name': 'test', 'age': '20'}
- json.dump():将json格式字符串写到文件中
import json
content = '{ "name": "test", "age": "20" }'
with open('text2.json','w',encoding='utf-8') as f :
json.dump(content,f)
输出结果:
"{ \"name\": \"test\", \"age\": \"20\" }"
- json.loads():将已编码的 JSON 字符串解码为 Python 对象
import json
content = '{"name":"test","age":"20"}'
print(type(json.loads(content)))
print(json.loads(content))
输出结果:
<class 'dict'>
{'name': 'test', 'age': '20'}
- json.dumps():将 Python 对象编码成 JSON 字符串
import json
content = '{"name":"test","age":"20"}'
print(type(json.dumps(content)))
print(json.dumps(content))
输出结果:
<class 'str'>
"{\"name\":\"test\",\"age\":\"20\"}"
网友评论