json 模块提供了一种很简单的方式来编码和解码JSON数据
其中两个主要的函数是 `json.dumps()` 和 `json.loads()`
1. `json.dumps` 将一个Python数据结构转换为 `str` 类型:
```python
data = {
'name': 'haha',
'age': 20,
}
json_str = json.dumps(data)
print(json_str)
print(type(json_str))
print(type(data))
```
输出结果:
```
{"name": "haha", "age": 20}
<class 'str'>
<class 'dict'>
```
2. `json.loads` 将一个JSON编码的字符串类型转换回一个Python数据结构:
```python
data2 = json.loads(json_str)
print(data2)
print(type(data2))
```
输出结果:
```
{'name': 'haha', 'age': 20}
<class 'dict'>
```
3. `json.dump()` 和 `json.load()` 用来编码和解码JSON数据,用于处理文件:
```python
with open('test.json', 'w') as f:
json.dump(data, f)
with open('test.json', 'r') as f:
data = json.load(f)
```
本文介绍了Python内置的json模块,用于处理JSON数据。主要函数`json.dumps()`将Python对象编码成JSON字符串,而`json.loads()`则将JSON字符串解码回Python数据结构。此外,`json.dump()`和`json.load()`则用于文件操作,实现JSON数据在文件中的读写。通过这些函数,开发者可以轻松地在Python程序和JSON格式之间进行数据转换。
1895

被折叠的 条评论
为什么被折叠?



