Python读写Json文件
json
适用于现代 C++ 的 JSON。
项目地址:https://gitcode.com/gh_mirrors/js/json
免费下载资源
·
主要方法
了解下面这 4 个 Python 的方法,处理 json 基本读写转换就没问题了。
dump()
将字典数据写入到 json 文件load()
读取 json 文件,返回字典格式dumps()
将字典格式数据转换成 json 字符串loads()
将 json 字符串转换成字典格式
代码测试
test.py
如下
import json
def WriteJson():
# 将字典数据写入到json文件中
print('写Json:')
dict1 = {'name': '小明', 'age': 5, 'sex': '男'}
with open('test.json','w',encoding='utf8')as fp:
#ensure_ascii=False 就不会用 ASCII 编码,中文就可以正常显示了
json.dump(dict1,fp,ensure_ascii=False)
def ReadJson():
# 读取json文件内容,返回字典格式
print('读Json:')
with open('test.json','r',encoding='utf8')as fp:
json_data = json.load(fp)
print(json_data)
print(type(json_data))
def Dict2Str():
# 将字典格式数据转换成json格式
print('dit转str:')
dict1 = {'name': '小明', 'age': 5, 'sex': '男'}
print(json.dumps(dict1,ensure_ascii=False))
print(type(json.dumps(dict1,ensure_ascii=False)))
def Str2Dict():
# 将json字符串转换成字典格式
print('str转dict:')
str1 = '{"name": "小明", "age": 5, "sex": "男"}'
print(json.loads(str1))
print(type(json.loads(str1)))
if __name__ == "__main__":
WriteJson()
ReadJson()
Dict2Str()
Str2Dict()
运行结果
D:\> python test.py
写Json:
读Json:
{'name': '小明', 'age': 5, 'sex': '男'}
<class 'dict'>
dit转str:
{"name": "小明", "age": 5, "sex": "男"}
<class 'str'>
str转dict:
{'name': '小明', 'age': 5, 'sex': '男'}
<class 'dict'>
GitHub 加速计划 / js / json
18
5
下载
适用于现代 C++ 的 JSON。
最近提交(Master分支:3 个月前 )
2134cb94
* change NLOHMANN_JSON_FROM_WITH_DEFAULT to let NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT work with an empty JSON instance
* fix ci_static_analysis_clang (ci_clang_tidy)
* change NLOHMANN_JSON_FROM_WITH_DEFAULT to let NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT work with an empty JSON instance 4 天前
6057b31d
* :wrench: overwork astyle call
* :wrench: overwork astyle call
* :wrench: overwork astyle call
* :wrench: overwork astyle call
* :wrench: overwork astyle call
* :wrench: overwork astyle call
* :wrench: overwork astyle call
* :wrench: overwork astyle call
* :wrench: overwork astyle call
* :wrench: overwork astyle call
* :wrench: overwork astyle call
* Use ubuntu-latest image to run Valgrind (#4575)
* :wrench: use Clang image to run valgrind
* :wrench: use Clang image to run valgrind
* :wrench: use Clang image to run valgrind
* :wrench: use Ubuntu image to run valgrind
* Use Clang image to run iwyu (#4574)
* :wrench: use Clang image to run iwyu
* :wrench: use Clang image to run iwyu
* :wrench: overwork astyle call
* :wrench: overwork astyle call
* :wrench: overwork astyle call
* :wrench: overwork astyle call
* :wrench: overwork astyle call
* :wrench: overwork astyle call
* :wrench: overwork astyle call
* :wrench: overwork astyle call
* :wrench: overwork astyle call
* :wrench: overwork astyle call
* :wrench: overwork astyle call
* :art: format code
* :hammer: clean up 6 天前
更多推荐
已为社区贡献8条内容
所有评论(0)