python 操作json
时间: 2023-12-09 17:35:58 浏览: 73
以下是Python操作JSON的示例代码:
1. 将Python对象编码为JSON字符串
```python
import json
# 将字典编码为JSON字符串
dict1 = {'A': 'a', 'B': 'b', 'C': 'c'}
en_json = json.dumps(dict1)
print(type(en_json), en_json)
# 将列表编码为JSON字符串
lst = ['aa', 'bb', 'cc']
lst_json = json.dumps(lst)
print(type(lst_json), lst_json)
# 将字符串编码为JSON字符串
s = 'I love you!'
s_json = json.dumps(s)
print(type(s_json), s_json)
# 注意:集合类型的对象是不可以JSON序列化的
_set = {'aaa', 'bbb'}
# set_json = json.dumps(_set) # 报错:TypeError: Object of type set is not JSON serializable
```
2. 将JSON字符串解码为Python对象
```python
import json
# 将JSON字符串解码为字典
en_json = '{"A": "a", "B": "b", "C": "c"}'
de_json = json.loads(en_json)
print(type(de_json), de_json)
# 将JSON字符串解码为列表
lst_json = '["aa", "bb", "cc"]'
de_json = json.loads(lst_json)
print(type(de_json), de_json)
# 将JSON字符串解码为字符串
s_json = '"I love you!"'
de_json = json.loads(s_json)
print(type(de_json), de_json)
# 注意:集合类型的对象是不可以JSON序列化的
# set_json = '{"aaa", "bbb"}'
# de_json = json.loads(set_json) # 报错:Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
```
3. 使用eval()解析JSON字符串(不推荐使用)
```python
import json
# 使用eval()解析JSON字符串
en_json = '{"X": "x", "Y": "y", "Z": "z"}'
de_json = eval(en_json)
print(type(de_json), de_json)
```
阅读全文