json数据转换
json本质就是一个固定格式字符串
json格式的字符串:【比字典两边对了一个单引号,并且jason里面的值,必须都用双引号括起来】
#json格式1,保存一组数据
stu1='{"name":"zhangsan","age":18,"hobby":"play"}'
#json保存多个学员信息
stus_s='[{"name":"zhangsan","age":18,"hobby":"play"},{"name":"lisi","age":18,"hobby":"play"},{"name":"wangqu","age":18,"hobby":"play"}]'和python的字典很像,python字典写法:
dicts = [{'id': 123, 'name': 'L'},{'id': 234, 'name': 'K'}]json转python【只能转换字典,或者列表嵌套字典。这两种python数据】
import json
def main():
# 保存一个学员json信息
stu1 = '{"name":"zhangsan","age":18,"hobby":"play"}'
# 保存多个学员json信息
stu2 ='[{"name":"zhangsan","age":18,"hobby":"play"},\
{"name":"lisi","age":18,"hobby":"play"},\
{"name":"wangqu","age":18,"hobby":"play"}]'
#json.loads,将json字符串转换成python对应的类型
pythonData=json.loads(stu1)
print(type(pythonData)) #打印数据类型。
print(pythonData) #打印python数据。
# 调用main函数
if __name__ == "__main__":
main()python转json
import json
def main():
# 保存一个学员python信息
stu1 = {"name":"zhangsan","age":18,"hobby":"play"}
#将python数据转换成json
pyjson=json.dumps(stu1,ensure_ascii=False) #ensure_ascii=False,禁止ascii转换
print(pyjson,type(pyjson)) #打印json数据,和数据类型
# 调用main函数
if __name__ == "__main__":
main()