我有两个JSON文档,我需要比较第一个对象的键是否存在使用Python中的第二个对象.他们俩都是嵌套的



我想比较这两个JSON文档的键,它们在其中嵌套了键,而不是根据其顺序。因此,如果JSON对象包含来自内容JSON对象的所有键。

内容json:

{
    "content": {
      "item": {
        "itemNo": "332972",
        "itemType": "COM",
        "description": "xxx"
      }
    }

定义JSON:

"definitions": {
      "Item": {
        "type": "object",
        "required": [
          "itemNo",
          "itemType"
        ],
        "properties": {
          "itemNo": {
            "type": "string",
            "example": "332972",
            "description": "Unique identifier for an Item"
          },
          "itemType": {
            "type": "string",
            "example": "COM",
            "description": "Defines the type of Item"
          },
          "description": {
            "type": "string",
            "example": "xxx"
          }
        }
      }
    }

我期望 true/success 输出以下两个JSON对象,因为所有密钥都存在于定义中JSON

我尝试了以下代码:

  for i in d.keys():
      array.append(i)
      for j in d[i].keys():
          array.append(j)
          wrapper = array
  return wrapper

,但我只从第一个巢中得到结果

这是一个简单递归函数的模板,该模板检查content中的每个键是否存在于definitions中的相应级别。它可能不足以满足您的特定需求,但应该很容易修改。

def verify_keys(content, definitions):
    for k,v in content.items():
        if k not in definitions:  # check key in this level
            return False
        if type(v) == dict and type(definitions[k]) == dict:
            if not verify_keys(v, definitions[k]):  # check recursively
                return False
    return True
...
with open('content.json', 'r') as content_file, open('definitions.json', 'r') as defs_file:
    content = json.loads(content_file.read())
    definitions = json.loads(defs_file.read())
print(verify_keys(content, definitions)

此解决方案的动态较小,而不是其他解决方案,但是如果提供的模式是您实际在做的。

假设content是您给出的第一个dict,而definitions是第二个。

cont_dict = content['content']['item']
def_dict = definitions['definitions']['Item']['properties']
result = True if set(cont_dict.keys()).issubset(def_dict.keys()) else False
print(result)

这可以是一条,但出于可读性,我做了几个。

我在实现2个函数时做到了。

第一个用于从定义中获取所有键的第一个

def get_keys(dl, keys_list):
                    if isinstance(dl, dict):
                        keys_list += dl.keys()
                        map(lambda x: get_keys(x, keys_list), dl.values())
                    elif isinstance(dl, list):
                        map(lambda x: get_keys(x, keys_list), dl)
                keys_list = []
                get_keys(definitions, keys_list)

,然后实现将通过上述列表的第二个功能(@green Cloak Guy重复使用(:

  def verify_keys(content, definitions):
                    for k,v in content.items():
                        if k not in keys_list:
                            return False
                        if type(v) == dict and type(definitions[k]) == dict:
                            if not verify_keys(v, definitions[k]):
                                return False
                    return True
                verify_keys(content, definitions)

最新更新