python-为给定的输入json定义类结构

时间:2019-04-24 22:00:43

标签: python json class parsing object

我有一个json,根据字段“ source”的值,它具有2种不同类型的子结构。样本json如下:

{
  "abc": "abc1",
  "value": [
    {
      "source": "s1",
      "value": [
        {
          "name": "n1",
          "value": [
            {
              "value": "v1"
            },
            {
              "value": "v2"
            }
          ]
        }
      ]
    },
    {
      "source": "s2",
      "value": [
        {
          "h1": "...",
          "h2": [
            {
              "h3": "..."
            },
            {
              "h3": "..."
            }
          ]
        }
      ]
    }
  ]
}

我写了部分/不完整的代码来用jsonstruct解析:

import json

import jsonstruct

def parse_json_obj(json_obj):
    json_str = json.dumps(json_obj)
    return jsonstruct.decode(json_str, ABCData)

class Entry(object):
    name = ""
    value = ""

class NameData(object):
    name = ""
    value = [Entry()]

class SourceData(object):
    source = ""
    value = [NameData()]

class ABCData(object):
    abc = ""
    value = [SourceData()]


a = parse_json_obj(<json_data_above>)
print a.value[0].source                # prints s1
print a.value[0].value[0].value[0].value       # prints v1

现在,我坚持如何扩展它以合并另一个源类型(s2)子结构。任何方向的帮助都将非常有用。谢谢!

0 个答案:

没有答案