您好,登錄后才能下訂單哦!
在Python語言中,json數據與dict字典以及對象之間的轉化,是必不可少的操作。
在Python中自帶json庫。通過import json導入。
在json模塊有2個方法,
下面是具體的示例:
dict字典轉json數據
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數據
'''
遇到問題沒人解答?小編創建了一個Python學習交流QQ群:579817333
尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書!
'''
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)
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
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數據轉成對象
'''
遇到問題沒人解答?小編創建了一個Python學習交流QQ群:579817333
尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書!
'''
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()方法的使用
'''
遇到問題沒人解答?小編創建了一個Python學習交流QQ群:579817333
尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書!
'''
import json
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()
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()
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。