6

I want to Json to Python class.

example

{'channel':{'lastBuild':'2013-11-12', 'component':['test1', 'test2']}}

self.channel.component[0] => 'test1'
self.channel.lastBuild    => '2013-11-12'

do you know python library of json converting?

2

2 Answers 2

24

Use object_hook special parameter in load functions of json module:

import json

class JSONObject:
  def __init__( self, dict ):
      vars(self).update( dict )

#this is valid json string
data='{"channel":{"lastBuild":"2013-11-12", "component":["test1", "test2"]}}'

jsonobject = json.loads( data, object_hook= JSONObject)

print( jsonobject.channel.component[0]  )
print( jsonobject.channel.lastBuild  )

This method have some issue, like some names in python are reserved. You can filter them out inside __init__ method.

Sign up to request clarification or add additional context in comments.

Comments

2

the json module will load a Json into a list of maps/list. e.g:

>>> import json
>>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
[u'foo', {u'bar': [u'baz', None, 1.0, 2]}]

see http://docs.python.org/2/library/json.html

If you want to deserialize into a Class instance, see this SO thread: Parse JSON and store data in Python Class

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.