【发布时间】:2013-12-04 04:46:24
【问题描述】:
我想将 Json 转换为 Python 类。
例子
{'channel':{'lastBuild':'2013-11-12', 'component':['test1', 'test2']}}
self.channel.component[0] => 'test1'
self.channel.lastBuild => '2013-11-12'
你知道json转换的python库吗?
【问题讨论】:
我想将 Json 转换为 Python 类。
例子
{'channel':{'lastBuild':'2013-11-12', 'component':['test1', 'test2']}}
self.channel.component[0] => 'test1'
self.channel.lastBuild => '2013-11-12'
你知道json转换的python库吗?
【问题讨论】:
在json模块的加载函数中使用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__ 方法中过滤掉它们。
【讨论】:
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
如果你想反序列化成一个 Class 实例,请看这个 SO 线程:Parse JSON and store data in Python Class
【讨论】: