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

发布于 2025-01-19 19:30:53 字数 1703 浏览 2 评论 0原文

我有两个 json 如下: json1:这是我提交给 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,并且 verify_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:字段、已验证的用例、分类实际上都是用逗号分隔的多值,因此您可以看到错误 json 中的“0”

提前感谢

I have two jsons as follows:
json1:This is the payload I am submitting to an 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: this is the response of an API call which tells me the error in the data that was posted


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

I want to produce a very user friendly response to the posted payload stating such and such an object has an invalid entry hence it has failed.

For the above, I need to map (or lookup) on the "id" from json2 to json1 and fetch the object_type and also that the entry in the verified_use_cases, classifications is wrong with corresponding id.

What I have tried so far:

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])

Now this gives me the object_id, but I am not sure how I can map it further with json1.

Kindly help.

PS: the fields, verified use cases, classifications are all multi valued with comma separated actually, hence you can see the "0" int the error json

Thanks in advance

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

贱贱哒 2025-01-26 19:30:53
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."]
                }
            }
        }
    }
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
    

Response

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."]
                }
            }
        }
    }
对岸观火 2025-01-26 19:30:53

您应该考虑以下几点:

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

因此,当您想创建任何这些已定义的类时,您可以执行以下操作:

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

You should consider a couple of things in mind:

  1. When you are working with APIs, make sure that you use some kind of validation or preprocesses, I suggest you to use Pydantic with it's validators and easiest ways of converting any json to necessary class.
  2. Example of using pydantic with your code, example will be below.
  3. Taking look at docs, here it is: https://pydantic-docs.helpmanual.io/

And as a result when you'd like to create any of these defined classes you can do:

parse_obj_as(ApiObject, response.json)

Example:

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")

Hm here's the how would I do this:

# 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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文