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数据

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)
    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数据转成对象

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

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()

实例演示如下: 

import json
import os

from Demo20210201.Person import Person

# dict字典转json数据-也即是str
L = dict(name='加菲猫', age=28, sex='男')
j = json.dumps(L)
print(type(j))
print(f'打印json str:{j}')

# 对象转json数据
person = Person('Tom', 20, '男')
print(f'打印person对象:{person}')
print(f'打印person.name:{person.name}')
print(f'打印person.age:{person.age}')
print(f'打印person.sex:{person.sex}')
print(type(person))
# 将对象转成dict字典
person = person.__dict__
print(type(person))
print(f'打印字典:{person}')
j = json.dumps(obj=person)
print(type(j))
print(f'打印json str:{j}')

# 对象转json串 也即是str(需要先把对象转成dict字典)
person = Person('John', 22, 'male')
j = json.dumps(obj=person.__dict__)
print(type(j))
print(j)

# json数据转成dict字典
print(type(j))
dict = json.loads(s=j)
print(type(dict))
print(dict)

with open('person.json', 'w') as f:
    json.dump(dict, f)  # 会在目录下生成一个person.json文件,文件内容是dict数据转换为json数据

# json数据转成对象
person = Person()
person.__dict__ = json.loads(s=j)
print(type(person))
print(person.name)

# 小结:json字符串 - dict - 对象,dict是中间转换的桥梁

# 读取json文件里字符串内容转换为字典
with open('person.json', 'r') as f:
    dict = json.load(fp=f)
print(type(dict))
print(dict)

targetPath = os.path.abspath('../')
filename = 'person.json'
print(targetPath)
targetFilePath = os.path.join(targetPath, filename)
print(targetFilePath)
with open(targetFilePath, 'r') as f:
    dict = json.load(fp=f)
print(dict)