Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

json

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.

like image 265
Mark Avatar asked Sep 27 '26 15:09

Mark


2 Answers

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...

like image 168
Joran Beasley Avatar answered Sep 30 '26 12:09

Joran Beasley


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.

like image 42
Martijn Pieters Avatar answered Sep 30 '26 13:09

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!