python json读取
时间: 2023-10-18 16:17:50 浏览: 95
在 Python 中读取 JSON 数据可以使用内置的 json 模块,具体步骤如下:
1. 导入 json 模块:
```python
import json
```
2. 使用 `json.load()` 或 `json.loads()` 方法将 JSON 数据加载为 Python 对象。其中,`json.load()` 方法可以从文件中读取 JSON 数据,`json.loads()` 方法可以从字符串中读取 JSON 数据。例如:
从文件中读取 JSON 数据:
```python
with open('data.json', 'r') as f:
data = json.load(f)
```
从字符串中读取 JSON 数据:
```python
json_str = '{"name": "Alice", "age": 20}'
data = json.loads(json_str)
```
3. 将 Python 对象转换为 JSON 数据,可以使用 `json.dump()` 或 `json.dumps()` 方法。其中,`json.dump()` 方法可以将 Python 对象写入文件中,`json.dumps()` 方法可以将 Python 对象转换为字符串。例如:
将 Python 对象写入文件中:
```python
data = {'name': 'Bob', 'age': 25}
with open('data.json', 'w') as f:
json.dump(data, f)
```
将 Python 对象转换为字符串:
```python
data = {'name': 'Bob', 'age': 25}
json_str = json.dumps(data)
```
阅读全文
相关推荐
















