Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert json to python class? [duplicate]

Tags:

python

json

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?

like image 593
ash84 Avatar asked Aug 23 '26 12:08

ash84


2 Answers

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.

like image 104
Arpegius Avatar answered Aug 26 '26 03:08

Arpegius


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

like image 42
bpgergo Avatar answered Aug 26 '26 03:08

bpgergo



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!