import json
# 将 Python 对象编码为 JSON 字符串
data = {
"name": "Alice",
"age": 25,
"is_student": False,
"courses": ["Math", "Science"]
}
# 使用 json.dumps() 方法将 Python 字典转换为 JSON 字符串
json_data = json.dumps(data, indent=4)
print("Python 对象转 JSON 字符串:")
print(json_data)
# 将 JSON 字符串解码为 Python 对象
json_string = '{"name": "Bob", "age": 30, "is_student": true, "courses": ["History", "Geography"]}'
parsed_data = json.loads(json_string)
print("\nJSON 字符串转 Python 对象:")
print(parsed_data)
# 写入 JSON 数据到文件
with open('data.json', 'w') as json_file:
json.dump(data, json_file, indent=4)
print("\n已将数据写入 data.json 文件")
# 从文件读取 JSON 数据
with open('data.json', 'r') as json_file:
file_data = json.load(json_file)
print("\n从 data.json 文件读取的数据:")
print(file_data)
json
模块:首先需要导入 Python 的 json
模块,它提供了处理 JSON 数据的功能。json.dumps()
方法可以将 Python 字典等对象转换为 JSON 格式的字符串。indent=4
参数用于格式化输出,使 JSON 字符串更易读。json.loads()
方法可以将 JSON 字符串解析为 Python 字典或其他相应类型的对象。json.dump()
方法可以将 Python 对象直接写入文件中,保存为 JSON 格式。json.load()
方法可以从文件中读取 JSON 数据并解析为 Python 对象。这样,你就可以在 Python 中轻松地进行 JSON 数据的编码和解码操作了。
上一篇:python命令行
下一篇:python能干嘛
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站