python中JSON解析
时间: 2024-10-16 15:14:04 浏览: 40
在Python中,JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,常用于前后端数据交互。Python有一个内置的模块叫做`json`,用于处理JSON数据的编码和解码。
要解析JSON字符串,你可以使用`json.loads()`函数:
```python
import json
# JSON字符串
json_string = '{"name": "John", "age": 30, "city": "New York"}'
# 解析JSON
parsed_data = json.loads(json_string)
print(parsed_data) # 输出:{'name': 'John', 'age': 30, 'city': 'New York'}
```
如果你有一个包含JSON数据的文件(通常是`.json`格式),则可以使用`with open()`打开文件,然后用`json.load()`加载内容:
```python
with open('file.json', 'r') as f:
data_from_file = json.load(f)
```
`json.dump()`和`json.dumps()`则是用于将Python对象转换成JSON字符串的:
```python
data_to_write = {'name': 'Jane', 'age': 35}
json_string = json.dumps(data_to_write, indent=4) # 带有缩进美化输出
# 将JSON写入文件
with open('output.json', 'w') as f:
f.write(json_string)
```
阅读全文
相关推荐















