根据 python 中的 ID 值映射两个 json

mapping two json based on ID value in python

我有两个json如下: json1:This 是我提交给 API

的负载

    {
        "id": 0,
        "object_type": "SCHEMA",
        "object_meta": {
            "source_id": 1002,
            "database": "raw_exadata",
            "schema": "clv"
                       },
        "business_name": "",
        "business_logic": "",
        "verified_use_cases": ["p"],
        "classifications": ["bb464f04-f879-361c-95e5-42bcca6a9535"]
    }
,
    {
        "id": 1,
        "object_type": "TABLE",
        "object_meta": {
            "source_id": 1002,
            "database": "raw",
            "schema": "clv",
            "table": "clv_cust"
                       },
       
        "business_name": "",
        "business_logic": "",
        "verified_use_cases": [],
        "classifications": ["p"],
       
    }
]

json2:这是 API 调用的响应,它告诉我发布的数据中的错误


{
   "errors": {
      "0": {
         "verified_use_cases": {
            "0": [
               "Not a valid UUID."
            ]
         }
      },
      "1": {
         "classifications": {
            "0": [
               "Not a valid UUID."
            ]
         }
      }
   }
}

我想对已发布的负载生成一个非常用户友好的响应,说明某某对象具有无效条目,因此失败。

对于上述内容,我需要将“id”从 json2 映射(或查找)到 json1 并获取 object_type 以及verified_use_cases,对应id分类错误

到目前为止我尝试过的:

from collections import defaultdict

p=json.loads(response.text)
result=defaultdict(list)
for i in p['errors']:
    result['obj_id'].append(int(i))
    result['error'].append(p['errors'][i])

现在这给了我 object_id,但我不确定如何用 json1.

进一步映射它

请帮忙。

PS:字段、验证用例、分类都是多值的,实际上用逗号分隔,因此你可以看到错误中的“0” json

提前致谢

您应该考虑以下几点:

  1. 当您使用 API 时,请确保您使用某种验证或预处理,我建议您使用 Pydantic 及其验证器以及将任何 json 转换为必需的最简单方法class.
  2. 在您的代码中使用 pydantic 的示例,示例如下。
  3. 查看文档,这里是:https://pydantic-docs.helpmanual.io/

因此,如果您想创建任何这些已定义的 classes,您可以执行以下操作:

parse_obj_as(ApiObject, response.json)

示例:

class ApiObject(BaseModel):
    id: int = Field(alias="id")
    object_type: str = Field(alias="object_type")
    object_meta: ObjectMeta = Field(alias="object_meta")  # Same class with it's defined fields
    business_name: str = Field(alias="business_name")
    business_logic: str = Field(alias="business_logic")
    verified_use_cases: List[str] = Field(alias="verified_use_cases")
    classifications: List[str] = Field(alias="classification")

嗯,这是我该怎么做:

# dict {0: json[0], 1: json[1]}
json_map = {str(json.get("id", 0)): json for json in json1}
for key, value in json2.get("errors").items():
    if key in json_map:
        upd_json = json_map.get(key)
        upd_json["errors"] = value
        print(f"JSON with id {key} were updated")  # Just some logging that it was really updated
json1 = [{
        "id": 0,
        "object_type": "SCHEMA",
        "object_meta": {
            "source_id": 1002,
            "database": "raw_exadata",
            "schema": "clv"
                       },
        "business_name": "",
        "business_logic": "",
        "verified_use_cases": ["p"],
        "classifications": ["bb464f04-f879-361c-95e5-42bcca6a9535"]
    }
,
    {
        "id": 1,
        "object_type": "TABLE",
        "object_meta": {
            "source_id": 1002,
            "database": "raw",
            "schema": "clv",
            "table": "clv_cust"
                       },
       
        "business_name": "",
        "business_logic": "",
        "verified_use_cases": [],
        "classifications": ["p"],
       
    }
]

json2 = {
   "errors": {
      "0": {
         "verified_use_cases": {
            "0": [
               "Not a valid UUID."
            ]
         }
      },
      "1": {
         "classifications": {
            "0": [
               "Not a valid UUID."
            ]
         }
      }
   }
}

resp = {}

for record in json1:
    key = str(record["id"])
    if key in json2["errors"]:
        record['errors'] = json2["errors"][key]#adding json2
        resp[key] = record
    

回应

print(json.dumps(resp))
    {
        "0": {
            "id": 0,
            "object_type": "SCHEMA",
            "object_meta": {
                "source_id": 1002,
                "database": "raw_exadata",
                "schema": "clv"
            },
            "business_name": "",
            "business_logic": "",
            "verified_use_cases ": ["p "],
            "classifications ": ["bb464f04 - f879 - 361 c - 95e5 - 42 bcca6a9535 "],
            "errors ": {
                "verified_use_cases ": {
                    "0 ": ["Not a valid UUID."]
                }
            }
        },
        "1 ": {
            "id ": 1,
            "object_type ": "TABLE ",
            "object_meta ": {
                "source_id ": 1002,
                "database ": "raw ",
                "schema ": "clv ",
                "table ": "clv_cust "
            },
            "business_name ": "",
            "business_logic ": "",
            "verified_use_cases ": [],
            "classifications": ["p"],
            "errors": {
                "classifications": {
                    "0": ["Not a valid UUID."]
                }
            }
        }
    }