在Python中如何使用JSON
时间: 2024-04-16 11:27:26 浏览: 30
在 Python 中,可以使用内置的 `json` 模块来处理 JSON 数据。该模块提供了一组函数和方法,用于解析、序列化和操作 JSON 数据。
下面是一些常用的 JSON 操作示例:
1. 将 JSON 字符串解析为 Python 对象:
```python
import json
json_str = '{"name": "John", "age": 30, "city": "New York"}'
data = json.loads(json_str)
print(data)
```
2. 将 Python 对象序列化为 JSON 字符串:
```python
import json
data = {
"name": "John",
"age": 30,
"city": "New York"
}
json_str = json.dumps(data)
print(json_str)
```
3. 从文件中读取 JSON 数据:
```python
import json
with open('data.json', 'r') as file:
data = json.load(file)
print(data)
```
4. 将数据写入到 JSON 文件中:
```python
import json
data = {
"name": "John",
"age": 30,
"city": "New York"
}
with open('data.json', 'w') as file:
json.dump(data, file)
```
这些示例展示了使用 `json` 模块进行基本的 JSON 解析、序列化和文件操作。你可以根据需要使用其他函数和方法来处理更复杂的 JSON 数据。