如何将JSON转换为Python类?

6
我希望将Json转换成Python类。
示例:
{'channel':{'lastBuild':'2013-11-12', 'component':['test1', 'test2']}}

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

您知道 Python 用于转换 JSON 的库吗?


json - Alexander Zhukov
请参见将JSON数据转换为Python对象 - Milovan Tomašević
2个回答

24

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

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  )

这种方法有一些问题,比如某些名称在Python中是保留的。你可以在__init__方法中过滤掉它们。


2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接