首页后端开发PythonPython序列化-序列化和反序列化

Python序列化-序列化和反序列化

时间2023-04-25 03:03:02发布访客分类Python浏览682
导读:使用 JSON 模块将 Python 对象转换为 JSON 格式的字符串非常简单,只需调用 json.dumps( 函数并传递要序列化的 Python 对象即可。以下是示例代码:import json # 将 Python 对象转换为...

使用 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 对象。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!

python

若转载请注明出处: Python序列化-序列化和反序列化
本文地址: https://pptw.com/jishu/7893.html
python自定义 JSON 序列化 Python序列化-json

游客 回复需填写必要信息