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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# -*- coding: utf-8 -*-

import json

# dict字典转json数据
def dict_to_json():
dict = {}
dict['name'] = 'Joe.Ye'
dict['age'] = 20
dict['sex'] = 'male'
print(dict) # 输出: {'name': 'many', 'age': 10, 'sex': 'male'}
j = json.dumps(dict)
print(j) # 输出: {"name": "many", "age": 10, "sex": "male"}

# 对象转json数据
def obj_to_json():
stu = Student(1, 'Joe.Ye', 28, 'male', '18800000000', 'test@test.com')
print(type(stu)) # <class 'json_test.student.Student'>
stu = stu.__dict__ # 将对象转成dict字典
print(type(stu)) # <class 'dict'>
print(stu) # {'name': 'Joe.Ye', 'age': 28, 'sex': 'male', 'phone': '18800000000', 'email': 'test@test.com', 'id': 1}
j = json.dumps(obj=stu)
print(j) # {"name": "Joe.Ye", "age": 28, "sex": "male", "phone": "18800000000", "email": "test@test.com", "id": 1}

# json数据转成dict字典
def json_to_dict():
j = '{"id": 1, "name": "Joe.Ye", "age": 28, "sex": "male", "phone": "18800000000", "email": "test@test.com"}'
dict = json.loads(s=j)
print(dict) # {u'name': u'Joe.Ye', u'age': 28, u'sex': u'male', u'phone': u'18800000000', u'email': u'test@test.com', u'id': 1}

# json数据转成对象
def json_to_obj():
j = '{"id": 1, "name": "Joe.Ye", "age": 28, "sex": "male", "phone": "18800000000", "email": "test@test.com"}'
dict = json.loads(s=j)
stu = Student()
stu.__dict__ = dict
print('id: ' + str(stu.id) + ', name: ' + stu.name + ', age: ' + str(stu.age) + ', sex: ' + str(stu.sex) +
', phone: ' + stu.phone + ', email: ' + stu.email) # id: 1, name: Joe.Ye, age: 28, sex: male, phone: 18800000000, email: test@test.com


class Student():
# Python通过参数默认值方式实现构造函数重载
def __init__(self, id=0, name='', age=0, sex='', phone='', email=''):
self.id = id
self.name = name
self.age = age
self.sex = sex
self.phone = phone
self.email = email

# dump()方法的使用
def dict_to_json_write_file():
dict = {}
dict['name'] = 'Joe.Ye'
dict['age'] = 10
dict['sex'] = 'male'
print(dict) # {'age': 10, 'name': 'Joe.Ye', 'sex': 'male'}
with open('test.json', 'w') as f:
json.dump(dict, f) # 会在目录下生成一个test.json的文件,文件内容是dict数据转成的json数据

# load()方法的使用
def json_file_to_dict():
with open('test.json', 'r') as f:
dict = json.load(fp=f)
print(dict) # {u'age': 10, u'name': u'Joe.Ye', u'sex': u'male'}


if __name__ == '__main__':
dict_to_json()
obj_to_json()
json_to_dict()
json_to_obj()
dict_to_json_write_file()
json_file_to_dict()

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :