使用 JSON 模块将 Python 对象转换为 JSON 格式的字符串非常简单,只需调用 json.dumps() 函数并传递要序列化的 Python 对象即可。以下是示例代码:
import json
# 将 Python 对象转换为 JSON 格式的字符串
data = {
'name': 'Alice',
'age': 30,
'is_student': True,
'hobbies': ['reading', 'coding', 'travelling'],
'address': {
'city': 'New York',
'state': 'NY'
}
}
json_string = json.dumps(data)
print(json_string)
# 将 JSON 格式的字符串转换为 Python 对象
data = json.loads(json_string)
print(data)
输出:
{"name": "Alice", "age": 30, "is_student": true, "hobbies": ["reading", "coding", "travelling"], "address": {"city": "New York", "state": "NY"}}
{'name': 'Alice', 'age': 30, 'is_student': True, 'hobbies': ['reading', 'coding', 'travelling'], 'address': {'city': 'New York', 'state': 'NY'}}
json.dumps() 函数还支持将 Python 对象转换为 JSON 格式的文件。以下是将 Python 对象写入文件的示例:
import json
# 将 Python 对象写入文件中的 JSON 格式
data = {
'name': 'Alice',
'age': 30,
'is_student': True,
'hobbies': ['reading', 'coding', 'travelling'],
'address': {
'city': 'New York',
'state': 'NY'
}
}
with open('data.json', 'w') as file:
json.dump(data, file)
# 从文件中读取 JSON 格式的数据并转换为 Python 对象
with open('data.json', 'r') as file:
data = json.load(file)
print(data)
输出:
{'name': 'Alice', 'age': 30, 'is_student': True, 'hobbies': ['reading', 'coding', 'travelling'], 'address': {'city': 'New York', 'state': 'NY'}}
在此示例中,我们使用了 json.dump() 函数将 Python 对象写入文件,然后使用 json.load() 函数从文件中读取 JSON 格式的数据并将其转换为 Python 对象。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。