python中的json数据转换

例子

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)

输出:

[{“name”: “张三”, “age”: 22}, {“name”: “李四”, “age”: 21}, {“name”: “王五”, “age”: 32}]

{“name”: “陈奕迅”, “song”: “苦瓜”}

[{‘name’: ‘张三’, ‘age’: 22}, {‘name’: ‘李四’, ‘age’: 21}, {‘name’: ‘王五’, ‘age’: 32}]

{‘name’: ‘陈奕迅’, ‘song’: ‘苦瓜’}

你可能感兴趣的:(python,python,json)