python中json库怎么用
时间: 2023-12-26 11:06:52 浏览: 123
Python中的json库可以用来处理JSON格式的数据。JSON是一种轻量级的数据交换格式,通常用于前后端数据交互。
以下是使用json库的基本方法:
1. 导入json库
```python
import json
```
2. 将Python对象转换为JSON格式
```python
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
json_data = json.dumps(my_dict)
print(json_data)
```
输出结果:
```python
{"name": "John", "age": 30, "city": "New York"}
```
3. 将JSON格式的数据转换为Python对象
```python
json_data = '{"name": "John", "age": 30, "city": "New York"}'
my_dict = json.loads(json_data)
print(my_dict)
```
输出结果:
```python
{'name': 'John', 'age': 30, 'city': 'New York'}
```
4. 读取JSON格式的文件
```python
with open('data.json', 'r') as f:
my_dict = json.load(f)
print(my_dict)
```
5. 将Python对象写入JSON格式的文件
```python
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
with open('data.json', 'w') as f:
json.dump(my_dict, f)
```
阅读全文
相关推荐
















