Python class to JSON -
this question has answer here:
- how make class json serializable 20 answers
i have requirement i'd construct lot of json objects. , there many different definitions , ideally want manage them classes , construct objects , dump them json on demand.
is there existing package/recipe let's me following
for keeping simple lets need represent people working, studying or both:
[{ "name": "foo", "jobinfo": { "jobtitle": "sr manager", "salary": 4455 }, "name": "bar", "courseinfo": { "coursetitle": "intro 101", "units": 3 }]
i'd create objects can dump valid json, created regular python classes.
i'd define classes db model:
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() # should print json example above
edit
i wrote own mini-framework accomplish this. available via pip
pip install pymodjson
code , examples available here: (mit) https://github.com/saravanareddy/pymodjson
you can create json
filtering __dict__
of object.
the working code:
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 = {} k, v in self.__dict__.iteritems(): if v 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() person in persons] print json.dumps(person_list)
Comments
Post a Comment