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:
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.
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...
Take a look at the colander project; it let's you define an object-oriented 'schema' that is easily serializable to and from JSON.
import colander
class Item(colander.MappingSchema):
thing = colander.SchemaNode(colander.String(),
validator=colander.OneOf(['foo', 'bar']))
flag = colander.SchemaNode(colander.Boolean())
language = colander.SchemaNode(colander.String()
validator=colander.OneOf(supported_languages)
class Items(colander.SequenceSchema):
item = Item()
Then load these from JSON:
items = Items().deserialize(json.loads(jsondata))
and colander validates the data for you, returning a set of python objects that then can be acted upon.
Alternatively, you'd have to create specific per-object handling to be able to turn Python objects into JSON structures and vice-versa.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With