python读写json
时间: 2023-08-01 15:12:44 浏览: 132
python如何读写json数据
5星 · 资源好评率100%
读取JSON文件可以使用json模块的load函数来读取json文件,代码如下:
```python
import json
with open('data.json', 'r') as f:
data = json.load(f)
```
另外,也可以使用json模块的loads函数来读取json字符串,代码如下:
```python
import json
with open('data.json', 'r') as f:
data_str = f.read()
data = json.loads(data_str)
```
写入JSON文件可以使用json模块的dump函数来写入json文件,代码如下:
```python
import json
data = {'name': 'Tom', 'age': 18}
with open('data.json', 'w') as f:
json.dump(data, f)
```
另外,也可以使用json模块的dumps函数将字典转换为json字符串并写入文件,代码如下:
```python
import json
data = {'name': 'Tom', 'age': 18}
with open('data.json', 'w') as f:
data_str = json.dumps(data)
f.write(data_str)
```
以上是使用json模块进行读写json文件的方法。\[1\]\[2\]
#### 引用[.reference_title]
- *1* *2* [python读写json文件方法详解](https://blog.csdn.net/qq_42751978/article/details/130668983)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down1,239^v3^insert_chatgpt"}} ] [.reference_item]
- *3* [Python读写json数据详解](https://blog.csdn.net/qq_37189082/article/details/124654767)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down1,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
阅读全文