python - 如何将 json 转换为 python 类?

标签 python json

<分区>

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

关于python - 如何将 json 转换为 python 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20091760/

相关文章:

python ,PIL;文本到图像和字体

python - 从分层 DataFrame 中按最大值选择行

c# - 使用 Json.Net 反序列化对象数组

php - PHP:如何解析从YouTube JSON响应派生的关联数组?

javascript - 如何在javascript中制作Json数组

Python:If-else 语句

python - 将 lambda 函数应用于具有 NaN 值的数据框?

python - python中多边形绘图的亚像素精度?

php - JavaScript 到 PHP 的安全性

javascript - JS 中循环包含对象数组的对象