json 包含两种不同类型的字典的Pydantic列表,但两者都不包含

wn9m85ua  于 2023-11-20  发布在  其他
关注(0)|答案(1)|浏览(90)

我似乎无法解决这个问题。

{"sourceInfo": {
      "list": [
        {
          "Ec2AssetSourceSimple": {
            "instanceType": "t2.micro",
            "subnetId": "subnet-xxxxxxxx",
            "imageId": "ami-xxxxxxxx",
            "groupName": "AutoScaling-Security-Group-1",
            "accountId": "xxxxxxxxx",
            "macAddress": "12:5e:2e:xxxxxxx",
            "reservationId": "r-xxxxxxx",
            "instanceId": "i-xxxxxxxxx",
            "monitoringEnabled": "false",
            "spotInstance": "false",
            "zone": "VPC",
            "instanceState": "RUNNING",
            "privateDnsName": "ip-xxxxxxx.ec2.internal",
            "vpcId": "vpc-xxxxxxx",
            "type": "EC_2",
            "availabilityZone": "us-east-1b",
            "privateIpAddress": "xxxxxx",
            "firstDiscovered": "2022-08-18T22:23:04Z",
            "ec2InstanceTags": {
              "tags": {
                "list": []
              }
            },
            "publicIpAddress": "xxxxxxxx",
            "lastUpdated": "2022-08-31T01:09:09Z",
            "region": "us-east-1",
            "assetId": xxxxxxx,
            "groupId": "sg-xxxxxxx",
            "localHostname": "ip-xxxxxxxx.ec2.internal",
            "publicDnsName": "ec2-xxxxxx.compute-1.amazonaws.com"
          }
        },
        {
          "AssetSource": {}
        }
      ]
    }}

字符串
对应的Pydantic类定义

class Ec2AssetSourceSimple(BaseModel):
    instanceType: str
    subnetId: str
    imageId: str
    groupName: str
    accountId: str
    macAddress: str
    reservationId: str
    ...

class AssetSource(BaseModel):
    pass

class SourceInfoItem(BaseModel):
    Ec2AssetSourceSimple: Optional[Ec2AssetSourceSimple] = None
    AssetSource: Optional[AssetSource] = None

class SourceInfo(BaseModel):
    list: List[SourceInfoItem]


总是导致以下异常

ValidationError: 2 validation errors for QualysHost
sourceInfo.list.0.AssetSource
  Field required [type=missing, input_value={'Ec2AssetSourceSimple': ...mpute-1.amazonaws.com'}}, input_type=dict]
    For further information visit https://errors.pydantic.dev/2.5/v/missing
sourceInfo.list.1.Ec2AssetSourceSimple
  Field required [type=missing, input_value={'AssetSource': {}}, input_type=dict]
    For further information visit https://errors.pydantic.dev/2.5/v/missing


内部字典没有一个键,所以Pydantic正在寻找两个类都出现,但显然不是这样。我如何强制它为Optional?

lh80um4z

lh80um4z1#

解决方案是删除名为SourceInfoItem的中间类,并在SourceInfo类下定义类:

class Ec2AssetSourceSimple(BaseModel):
    instanceType: str
    subnetId: str
    imageId: str
    ...

class AssetSource(BaseModel):
    pass

class SourceInfo(BaseModel):
    list: Optional[List[Union[Ec2AssetSourceSimple, AssetSource, None]]]

字符串

相关问题