1

I have a requirement where I'd like to construct a lot of JSON objects. And there are many different definitions and ideally I want to manage them like classes and construct objects and dump them to JSON on demand.

Is there an existing package/recipe that let's me do the following

For keeping it simple lets say I need to represent people who are working, studying or both:

[{
  "Name": "Foo",
  "JobInfo": {
    "JobTitle": "Sr Manager",
    "Salary": 4455
 },
 {
  "Name": "Bar",
  "CourseInfo": {
    "CourseTitle": "Intro 101",
    "Units": 3
}]

I'd like to create objects that can dump valid JSON, but created like regular python classes.

I'd like to define my classes like a 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()  # this should print the JSON example from above

EDIT

I wrote my own mini-framework to accomplish this. Its available via pip

pip install pymodjson

Code and examples are available here: (MIT) https://github.com/saravanareddy/pymodjson

sisanared
  • 4,175
  • 2
  • 27
  • 42
  • 2
    [See here](http://stackoverflow.com/questions/3768895/how-to-make-a-class-json-serializable). For the validation part, you need to write your own `JSONEncoder`. – Sevanteri Sep 13 '16 at 05:03

1 Answers1

2

You can create the json by carefully filtering from the __dict__ of the 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 = {}
        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)  
praba230890
  • 2,192
  • 21
  • 37