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?

ash84
  • 787
  • 3
  • 12
  • 33

2 Answers2

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.

Arpegius
  • 5,817
  • 38
  • 53
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

Community
  • 1
  • 1
bpgergo
  • 15,669
  • 5
  • 44
  • 68