了解Json

在开始学习Python中的json模块之前,我们需要了解什么是Json。Json是一种轻量级的数据交换格式,常用于前后台数据传输和存储。它采用人类可读的文本格式,并且易于解析和生成。在Json中,数据以键值对的形式存储,并可以按照特定的规则进行嵌套。Json格式可以表示各种类型的数据,包括数字、字符串、布尔值、数组和对象。Python中的json模块提供了一组方法,用于处理和解析Json数据。

Json与Python数据类型的转换

json模块提供了两组方法,用于 Json 和 Python 数据类型之间的转换。它定义了四个函数,分别是:dumps()、dump()、loads() 和 load()。

序列化和反序列化

序列化是指将 Python 对象转换为 Json 格式的过程,而反序列化则是将 Json 数据转换为 Python 对象的过程。

1. 序列化:使用 dumps() 函数将 Python 对象转换为 Json 字符串


import json

data = {
    'name': 'John',
    'age': 30,
    'city': 'New York'
}

json_str = json.dumps(data)
print(json_str)  # 输出结果:{"name": "John", "age": 30, "city": "New York"}

2. 反序列化:使用 loads() 函数将 Json 字符串转换为 Python 对象


import json

json_str = '{"name": "John", "age": 30, "city": "New York"}'

data = json.loads(json_str)
print(data)  # 输出结果:{'name': 'John', 'age': 30, 'city': 'New York'}

3. 序列化到文件:使用 dump() 函数将 Python 对象序列化并写入文件


import json

data = {
    'name': 'John',
    'age': 30,
    'city': 'New York'
}

with open('data.json', 'w') as f:
    json.dump(data, f)

4. 从文件反序列化:使用 load() 函数从文件中读取 Json 数据并反序列化为 Python 对象


import json

with open('data.json', 'r') as f:
    data = json.load(f)

print(data)  # 输出结果:{'name': 'John', 'age': 30, 'city': 'New York'}