python json库

admin 45 0

# Python JSON库详解

JSON (JavaScript Object Notation) 是一种轻量级的数据交换格式,常用于服务器和网页应用之间的数据交换,Python 的 json 库提供了编码和解码 JSON 数据的功能。

### 1. 安装和使用 Python JSON 库

Python 自带了 JSON 库,无需额外安装,可以直接使用 `import json` 来导入 JSON 库。

### 2. JSON 数据格式

JSON 数据格式通常包括键值对(key-value pair)和数组,键值对是由冒号分隔的键和值,数组是由方括号包含的逗号分隔的值。

{
  "name": "John",
  "age": 30,
  "city": "New York",
  "hobbies": ["reading", "music", "sports"]
}

### 3. JSON 库的功能

Python JSON 库提供了以下功能:

* `json.loads(string)`:将 JSON 字符串解码为 Python 对象(通常是字典或列表)。

* `json.dumps(obj)`:将 Python 对象编码为 JSON 字符串。

* `json.load(fp)`:从文件对象中读取 JSON 数据并解码为 Python 对象。

* `json.dump(obj, fp)`:将 Python 对象编码为 JSON 数据并写入文件对象。

### 4. 使用示例

下面是一些使用 Python JSON 库的示例:

#### 示例 1:解码 JSON 字符串

import json

json_string = '{"name": "John", "age": 30, "city": "New York"}'
python_obj = json.loads(json_string)
print(python_obj)  # 输出:{'name': 'John', 'age': 30, 'city': 'New York'}

#### 示例 2:编码 Python 对象为 JSON 字符串

import json

python_obj = {'name': 'John', 'age': 30, 'city': 'New York'}
json_string = json.dumps(python_obj)
print(json_string)  # 输出:{"name": "John", "age": 30, "city": "New York"}

#### 示例 3:读取 JSON 文件并解码为 Python 对象

import json

with open('data.json', 'r') as file:
    python_obj = json.load(file)
    print(python_obj)  # 输出:{'name': 'John', 'age': 30, 'city': 'New York'}

#### 示例 4:将 Python 对象编码为 JSON 数据并写入文件

import json

python_obj = {'name': 'John', 'age': 30, 'city': 'New York'}
with open('data.json', 'w') as file:
    json.dump(python_obj, file)  # 将 python_obj 编码为 JSON 数据并写入文件。