Python将类序列化为JSON
我有一个需求,我想构造很多JSON对象。有很多不同的定义,理想情况下,我希望像管理类一样管理它们,构造对象,并根据需要将它们转储到JSON 是否有一个现有的包/配方让我做以下工作 为了保持简单,让我们假设我需要代表工作、学习或两者兼有的人:Python将类序列化为JSON,python,json,Python,Json,我有一个需求,我想构造很多JSON对象。有很多不同的定义,理想情况下,我希望像管理类一样管理它们,构造对象,并根据需要将它们转储到JSON 是否有一个现有的包/配方让我做以下工作 为了保持简单,让我们假设我需要代表工作、学习或两者兼有的人: [{ "Name": "Foo", "JobInfo": { "JobTitle": "Sr Manager", "Salary": 4455 }, { "Name": "Bar", "CourseInfo": {
[{
"Name": "Foo",
"JobInfo": {
"JobTitle": "Sr Manager",
"Salary": 4455
},
{
"Name": "Bar",
"CourseInfo": {
"CourseTitle": "Intro 101",
"Units": 3
}]
我想创建可以转储有效JSON的对象,但创建的对象类似于常规python类
我想将我的类定义为db模型:
class Person:
Name = String()
JobInfo = Job()
CourseInfo = Course()
class Job:
JobTitle = String()
Salary = Integer()
class Course:
CourseTitle = String()
Units = Integer()
persons = [Person("Foo", Job("Sr Manager", 4455)), Person("Bar", Course("Intro 101", 3))]
person_list = list(persons)
print person_list.to_json() # this should print the JSON example from above
编辑
我编写了自己的迷你框架来实现这一点。它可以通过pip获得
pip安装pymodjson
这里提供了代码和示例:(麻省理工学院)
您可以通过仔细地从对象的
\uuu dict\uuu
中筛选来创建json
工作守则:
import json
class Person(object):
def __init__(self, name, job=None, course=None):
self.Name = name
self.JobInfo = job
self.CourseInfo = course
def to_dict(self):
_dict = {}
for k, v in self.__dict__.iteritems():
if v is not None:
if k == 'Name':
_dict[k] = v
else:
_dict[k] = v.__dict__
return _dict
class Job(object):
def __init__(self, title, salary):
self.JobTitle = title
self.Salary = salary
class Course(object):
def __init__(self, title, units):
self.CourseTitle = title
self.Units = units
persons = [Person("Foo", Job("Sr Manager", 4455)), Person("Bar", Course("Intro 101", 3))]
person_list = [person.to_dict() for person in persons]
print json.dumps(person_list)
. 对于验证部分,您需要编写自己的jsonecoder
。