【问题标题】:how to convert json to python class? [duplicate]如何将json转换为python类? [复制]
【发布时间】: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库吗?

【问题讨论】:

标签: python json


【解决方案1】:

在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__ 方法中过滤掉它们。

【讨论】:

    【解决方案2】:

    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

    【讨论】:

      猜你喜欢
      • 2010-10-03
      • 2021-09-08
      • 2013-02-14
      • 2021-08-18
      • 2021-12-14
      • 2019-02-01
      • 2018-10-16
      • 2021-11-06
      • 2010-09-19
      相关资源
      最近更新 更多