Mark Mark - 1 month ago 23
JSON Question

Create a Python class that I can serialize into a nested JSON object

I'm a very beginner with Python classes and JSON and I'm not sure I'm going in the right direction.

Basically, I have a web service that accepts a JSON request in a POST body like this:

{ "item" :
{
"thing" : "foo",
"flag" : true,
"language" : "en_us"
},
"numresults" : 3
}


I started going down the route of creating a class for "item" like this:

class Item(object):
def __init__:
self.name = "item"

@property
def thing(self):
return self.thing

@thing.setter
def thing(self, value):
self.thing = value

...


So, my questions are:


  1. Am I going in the right direction?

  2. How do I turn the Python object into a JSON string?



I've found a lot of information about JSON in python, I've looked at jsonpickle, but I can't seem to create a class that ends up outputting the nested dictionaries needed.

EDIT:
Thanks to Joran's suggestion, I stuck with a class using properties and added a method like this:

def jsonify(self):
return json.dumps({ "item" : self.__dict__ }, indent=4)


and that worked perfectly.

Thanks everyone for your help.

Answer

just add one method to your class that returns a dictionary

def jsonify(self):
    return { 'Class Whatever':{
              'data1':self.data1,
               'data2':self.data2,
               ...
                               }

     }

and call your tojson function on the result ... or call it before your return to just return a json result...