您现在的位置是:首页 > 文章详情

Python中:dict(或对象)与json之间的互相转化

日期:2019-12-11点击:371

在Python语言中,json数据与dict字典以及对象之间的转化,是必不可少的操作。

在Python中自带json库。通过import json导入。

在json模块有2个方法,

  • loads():将json数据转化成dict数据
  • dumps():将dict数据转化成json数据
  • load():读取json文件数据,转成dict数据
  • dump():将dict数据转化成json数据后写入json文件

下面是具体的示例:

dict字典转json数据

#Python学习交流QQ群:579817333 import json def dict_to_json(): dict = {} dict['name'] = 'many' dict['age'] = 10 dict['sex'] = 'male' print(dict) # 输出:{'name': 'many', 'age': 10, 'sex': 'male'} j = json.dumps(dict) print(j) # 输出:{"name": "many", "age": 10, "sex": "male"} if __name__ == '__main__': dict_to_json()

对象转json数据

import json def obj_to_json(): stu = Student('007', '007', 28, 'male', '13000000000', '123@qq.com') print(type(stu)) # <class 'json_test.student.Student'> stu = stu.__dict__ # 将对象转成dict字典 print(type(stu)) # <class 'dict'> print(stu) # {'id': '007', 'name': '007', 'age': 28, 'sex': 'male', 'phone': '13000000000', 'email': '123@qq.com'} j = json.dumps(obj=stu)#Python学习交流QQ群:579817333 print(j) # {"id": "007", "name": "007", "age": 28, "sex": "male", "phone": "13000000000", "email": "123@qq.com"} if __name__ == '__main__': obj_to_json()

json数据转成dict字典

import json #Python学习交流QQ群:579817333 def json_to_dict(): j = '{"id": "007", "name": "007", "age": 28, "sex": "male", "phone": "13000000000", "email": "123@qq.com"}' dict = json.loads(s=j) print(dict) # {'id': '007', 'name': '007', 'age': 28, 'sex': 'male', 'phone': '13000000000', 'email': '123@qq.com'} if __name__ == '__main__': json_to_dict()

json数据转成对象

import json def json_to_obj(): j = '{"id": "007", "name": "007", "age": 28, "sex": "male", "phone": "13000000000", "email": "123@qq.com"}' dict = json.loads(s=j) stu = Student() stu.__dict__ = dict print('id: ' + stu.id + ' name: ' + stu.name + ' age: ' + str(stu.age) + ' sex: ' + str( stu.sex) + ' phone: ' + stu.phone + ' email: ' + stu.email) # id: 007 name: 007 age: 28 sex: male phone: 13000000000 email: 123@qq.com if __name__ == '__main__': json_to_obj()

json的load()与dump()方法的使用

  • dump()方法的使用
import json #Python学习交流QQ群:579817333 def dict_to_json_write_file(): dict = {} dict['name'] = 'many' dict['age'] = 10 dict['sex'] = 'male' print(dict) # {'name': 'many', 'age': 10, 'sex': 'male'} with open('1.json', 'w') as f: json.dump(dict, f) # 会在目录下生成一个1.json的文件,文件内容是dict数据转成的json数据 if __name__ == '__main__': dict_to_json_write_file()
  • load()的使用
import json def json_file_to_dict(): with open('1.json', 'r') as f: dict = json.load(fp=f) print(dict) # {'name': 'many', 'age': 10, 'sex': 'male'} if __name__ == '__main__': json_file_to_dict()
原文链接:https://yq.aliyun.com/articles/739121
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章