JSON是一种轻量级的数据交互格式,JSON本质上是带有特定格式的字符串,负责不同编程语言重的数据传递和交互
# 导入内置json模块
import json
# 准备列表,列表每个元素都是字典,转化为json
list = [{'it':'wk', 'age': 16}, {'it':'wk', 'age': 17}, {'it':'wk', 'age': 18}]
json_str = json.dumps(list, ensure_ascii=False) # 如果要写中文就传入ensure_ascii=False
print(type(json_str)) # <class 'str'>
print(json_str)
# 准备字典,将字典内容转换为json
dict = {'it':'wk', 'age': 16}
json_str = json.dumps(dict)
print(type(json_str)) # <class 'str'>
print(json_str)
# 将json字符串转换为python数据类型list
s = '[{"it":"wk", "age": 16}, {"it":"wk", "age": 17}, {"it":"wk", "age": 18}]'
l = json.loads(s)
print(type(l)) # <class 'list'>
print(l)
# 将json字符串转换为python数据类型dict
s = '{"it":"wk", "age": 16}'
l = json.loads(s)
print(type(l)) # <class ‘dict'>
print(l)