在Python中,JSON(JavaScript Object Notation)数据的转换是非常常见的操作。Python内置了json模块,它提供了用于编码和解码JSON数据的功能。
将Python对象转换为JSON数据
你可以使用json.dumps()函数将Python对象(如字典、列表等)转换为JSON格式的字符串。
python复制代码
import json | |
# Python对象 | |
data = { | |
"name": "John", | |
"age": 30, | |
"city": "New York" | |
} | |
# 转换为JSON字符串 | |
json_string = json.dumps(data) | |
print(json_string) | |
# 输出: {"name": "John", "age": 30, "city": "New York"} |
将JSON数据转换为Python对象
你可以使用json.loads()函数将JSON格式的字符串转换为Python对象。
python复制代码
import json | |
# JSON字符串 | |
json_string = '{"name": "John", "age": 30, "city": "New York"}' | |
# 转换为Python对象(字典) | |
data = json.loads(json_string) | |
print(data) | |
# 输出: {'name': 'John', 'age': 30, 'city': 'New York'} |
从文件中读取和写入JSON数据
你还可以使用json模块读取和写入JSON文件。
写入JSON文件
python复制代码
import json | |
# Python对象 | |
data = { | |
"name": "John", | |
"age": 30, | |
"city": "New York" | |
} | |
# 写入JSON文件 | |
with open('data.json', 'w') as file: | |
json.dump(data, file) |
读取JSON文件
python复制代码
import json | |
# 读取JSON文件 | |
with open('data.json', 'r') as file: | |
data = json.load(file) | |
print(data) | |
# 输出: {'name': 'John', 'age': 30, 'city': 'New York'} |
在上面的例子中,json.dump()函数用于将Python对象写入JSON文件,而json.load()函数用于从JSON文件中读取数据并转换为Python对象。
确保在写入或读取文件时,文件路径是正确的,并且你有足够的权限来执行这些操作。
这些是在Python中处理JSON数据的基本方法。json模块还提供了其他高级功能,如json.JSONEncoder和json.JSONDecoder类,用于自定义编码和解码过程。
8472

被折叠的 条评论
为什么被折叠?



