我想把Json转到Python类。
示例
{'channel':{'lastBuild':'2013-11-12', 'component':['test1', 'test2']}}
self.channel.component[0] => 'test1'
self.channel.lastBuild => '2013-11-12'你知道json转换的python库吗?
发布于 2013-11-20 19:25:54
在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__方法中过滤掉它们。
发布于 2013-11-20 17:24:13
json模块会将Json加载到映射列表/列表中。例如:
>>> import json
>>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
[u'foo', {u'bar': [u'baz', None, 1.0, 2]}]请参阅http://docs.python.org/2/library/json.html
如果您想反序列化为一个类实例,请参见SO线程:Parse JSON and store data in Python Class
https://stackoverflow.com/questions/20091760
复制相似问题