天天看點

Python中:dict(或對象)與json之間的互相轉化

在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', '[email protected]')
    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': '[email protected]'}
    j = json.dumps(obj=stu)#Python學習交流QQ群:579817333
    print(j)  # {"id": "007", "name": "007", "age": 28, "sex": "male", "phone": "13000000000", "email": "[email protected]"}
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": "[email protected]"}'
    dict = json.loads(s=j)
    print(dict)  # {'id': '007', 'name': '007', 'age': 28, 'sex': 'male', 'phone': '13000000000', 'email': '[email protected]'}


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": "[email protected]"}'
    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: [email protected]
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()