0

我对 Python 类有点陌生。我使用 python,但没有广泛使用类。所以这就是我想要做的,是读取 JSON 并将元素和节点转换为类和对象,所以我调用函数从 JSON 中获取值。

{
  "datamap": {
    "version": "1.0",
    "sourceProvider": "example_provider",
    "logicalTables": [
      {
        "name": "region_table_one",
        "physicalTable": "dbo_parent_user", 
        "logicalColumns": [
          {
            "name": "UID",
            "physicalColumnName": "uid_number",
            "displayName": "U Number",
            "logicalDataType": "integer",
            "inputType": {
              "inputAction": "number",
              "multiSelect": false
            },
          },
          {
            "name": "UID1",
            "physicalColumnName": "uid_number1",
            "displayName": "U Number1",
            "logicalDataType": "integer",
            "inputType": {
              "inputAction": "number",
              "multiSelect": false
            },
          },
        ]
      },
      {
        "name": "region_table_two",
        "physicalTable": "dbo_user_two", 
        "logicalColumns": [
          {
            "name": "UID2",
            "physicalColumnName": "uid_number2",
            "displayName": "U Number2",
            "logicalDataType": "integer",
            "inputType": {
              "inputAction": "number",
              "multiSelect": false
            },
          },
          {
            "name": "UID3",
            "physicalColumnName": "uid_number3",
            "displayName": "U Number3",
            "logicalDataType": "integer",
            "inputType": {
              "inputAction": "number",
              "multiSelect": false
            },
          },
        ]
      }
    ]
  }
}

我写的 Python 类:

import json

class DataMap(object):
    def __init__(self):
        with open('datamap.json') as f:
            self.__dict__ = json.load(f)

    def get_logical_table(self, tableName):
        if self.datamap['logicalTables']['name'] == tableName:
            return datamap['logicalTables']['name']

obj = DataMap()
print(obj.datamap['logicalTables'])
#print(obj.get_logical_table('logicalTables'))

  • 我想做的是,如果我打电话get_logical_table,我应该能够得到region_table_one and region_table_two
  • 如果我通过get_logical_table输出来获取该logicalColumnsJSON 对象的内部,是否有任何方法。

我正在引用:
- https://thepythonguru.com/reading-and-writing-json-in-python/ -将 json 字符串反序列化为 python 中的对象在 某种程度上,但坚持阅读课堂笔记。我在这里先向您的帮助表示感谢。

更新:

import json


class DataMap(object):
    def __init__(self):
        self.logical_tables = None
        with open('datamap.json') as f:
            self.__dict__ = json.load(f)
        self.data_map = self.__dict__['datamap']

    def get_map_id(self):
        return self.data_map['mapId']

    def get_version(self):
        return self.data_map['version']

    def get_region(self):
        return self.data_map['region']

    def get_source_provider(self):
        return self.data_map['sourceProvider']

    def __getitem__(self, key):
        return self.data_map[key]

    def __repr__(self):
        return repr(self.data_map)

    def __len__(self):
        return len(self.__dict__['datamap'])

    def copy(self):
        return self.data_map.copy()

    def has_key(self, k):
        return k in self.data_map

    def keys(self):
        return self.data_map.keys()

    def values(self):
        return self.data_map.values()

    def items(self):
        return self.data_map.items()

    def pop(self, *args):
        return self.data_map.pop(*args)

    def __contains__(self, item):
        return item in self.data_map

    def __iter__(self):
        return iter(self.data_map)


class LogicalTables(DataMap):
    def __init__(self):
        DataMap.__init__(self)
        self.logical_tables = self.data_map['logicalTables']

        logical_table = None
        for table in self.get_all_logical_tables():
            self.name = table.get("name")
        print(self.name)

    def __len__(self):
        return len(self.data_map['logicalTables'])

    def __repr__(self):
        return repr(self.logical_tables)

    def createName(self):
        self.name = "Temporary Value"

    def has_key(self, k, table_name=None):
        """Check if the dict has given key"""
        logical_table = self.get_logical_table(table_name)
        return k in logical_table

    def get_all_logical_tables(self, tableName=None):
        return self.data_map['logicalTables']

    def get_logical_table(self, table_name=None):
        logical_table = None
        for table in self.get_all_logical_tables():
            if table.get("name") == table_name:
                logical_table = table
        return logical_table

    def get_logical_table_list(self, table_name=None):
        table_list = []
        for table in self.get_all_logical_tables():
            table_list.append(table.get("name"))
        return table_list


class LogicalColumns(LogicalTables):
    def __init__(self):
        LogicalTables.__init__(self)
        self.logical_columns = self.logical_tables['logicalColumns']

    def __len__(self):
        return len(self.logical_columns['logicalColumns'])

    def __repr__(self):
        return repr(self.logical_columns)

我已经更新了,这是我目前的课程。

4

1 回答 1

2

logicalTables在你的 json 输入中实际上是 a list,而不是 a dict,所以你这样做是['logicalTables']['name']行不通的。

您需要更改get_logical_table为以下内容:

    def get_logical_table(self, tableName):
        for table in self.datamap['logicalTables']:
            if table['name'] == tableName:
                return table['logicalColumns']

与其遍历列表,不如转换您的列表,dict以便您可以直接访问任何列表(如果它们是唯一的)。logicalTablename

更新:

您可以dict像这样转换:

tables = {}
for table in self.datamap['logicalTables']:
    name = table['name']
    del table['name']
    tables[name] = table

self.datamap['logicalTables'] = tables

# Use like so:
table_one = self.datamap['logicalTables']['region_table_one']
于 2020-03-15T09:45:34.967 回答