Python 3 读写 json 文件

使用函数 json.dumps()、loads() 、json.dump()、json.load() 。

1 json.dumps() 将python对象编码成Json字符串

python 复制代码
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对象

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储存到文件中

python 复制代码
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对象提取出来

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': '北京'}
'''

参考:

python的JSON用法------dumps的各种参数用法(详细)_jsondump用法-CSDN博客

json.dump()与json_dumps()区别_json.dumps-CSDN博客

Python json.dumps()函数使用解析 | w3cschool笔记

相关推荐
dreamer_83993 小时前
AI智能合同比对系统:从零搭建实战教程
人工智能·python
AOwhisky4 小时前
Python 学习笔记(第十五期)——运维自动化(下·后篇):堡垒机实战——paramiko高阶篇
运维·python·学习·云原生·自动化·运维开发
观察员4 小时前
带你用一个 Python 图书系统,通关封装继承多态
python
林泽毅6 小时前
PyTRIO快速入门(一):概念、推理与训练
人工智能·python·深度学习·机器学习·语言模型
admin and root6 小时前
「移动安全」安卓APP 反编译&frida脱壳技巧分享
android·开发语言·python·web安全·微信小程序·移动安全·攻防演练
雪的季节6 小时前
Python基础5-18
开发语言·python
学术小李6 小时前
基于Pytorch,如何用CUDA自己写算子?(一)
人工智能·pytorch·python
ShirleyWang0127 小时前
让headlamp控制台能访问
linux·服务器·python·k8s·k3s
想会飞的蒲公英7 小时前
用 Streamlit 给文本分类模型做一个演示页面
人工智能·python·机器学习
老徐聊GEO7 小时前
亲测有效的AI品牌检测公司案例分享
大数据·人工智能·python