如何将json转换为python类?

ash*_*h84 2 python json

我想要Json到Python类.

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

self.channel.component[0] => 'test1'
self.channel.lastBuild    => '2013-11-12'
Run Code Online (Sandbox Code Playgroud)

你知道json转换的python库吗?

Arp*_*ius 15

object_hook在json模块的加载函数中使用特殊参数:

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  )
Run Code Online (Sandbox Code Playgroud)

这个方法有一些问题,比如python中的一些名字是保留的.您可以在__init__方法内过滤掉它们.