赞
踩
import json # 将【列表】转换为json数据 data = [{"name": "张三", "age": 22}, {"name": "李四", "age": 21}, {"name": "王五", "age": 32}] # ensure_ascii=False 表明不用ascii编码,而使用unicode编码,这样可显示中文 json_str = json.dumps(data, ensure_ascii=False) print(type(json_str)) print(json_str) # 将【字典】转换为json数据 d = {"name": "陈奕迅", "song": "苦瓜"} json_str = json.dumps(d, ensure_ascii=False) print(type(json_str)) print(json_str) # 将json字符串转换成 python 数据类型 list s = '[{"name": "张三", "age": 22}, {"name": "李四", "age": 21}, {"name": "王五", "age": 32}]' l = json.loads(s) print(type(l)) # list print(l) s = '{"name": "陈奕迅", "song": "苦瓜"}' l = json.loads(s) print(type(l)) # dict print(l)
输出:
<class ‘str’>
[{“name”: “张三”, “age”: 22}, {“name”: “李四”, “age”: 21}, {“name”: “王五”, “age”: 32}]
<class ‘str’>
{“name”: “陈奕迅”, “song”: “苦瓜”}
<class ‘list’>
[{‘name’: ‘张三’, ‘age’: 22}, {‘name’: ‘李四’, ‘age’: 21}, {‘name’: ‘王五’, ‘age’: 32}]
<class ‘dict’>
{‘name’: ‘陈奕迅’, ‘song’: ‘苦瓜’}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。