Python 中的 json数据格式使用方法
时间: 2024-03-28 20:05:29 浏览: 49
在 Python 中,可以使用内置的 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) # 输出:{'name': 'John', 'age': 30, 'city': 'New York'}
```
2. 将 Python 对象转换为 JSON 字符串(序列化):
```python
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"}
```
3. 读取 JSON 文件并解析为 Python 对象:
```python
import json
with open('data.json') as f:
data = json.load(f)
print(data) # 输出:文件中的 JSON 数据解析后的 Python 对象
```
4. 将 Python 对象写入 JSON 文件:
```python
import json
data = {"name": "John", "age": 30, "city": "New York"}
with open('data.json', 'w') as f:
json.dump(data, f)
```
这些方法可以帮助你在 Python 中处理 JSON 数据。你可以根据自己的需求选择适合的方法来操作 JSON 数据。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)