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:
- Am I going in the right direction?
- 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.