为嵌套(和递增)的Json定义Pydentic类

2fjabf4q  于 2023-05-30  发布在  其他
关注(0)|答案(1)|浏览(295)

下面是一个API端点的JSON响应。我想创建一个等价的pydentic类。

{
 "AllSeries": 
  {
    "s1": {
        "s_id": 1,
        "s_name": "Apple"
    },
    "s2": {
        "s_id": 2,
        "s_name": "Basket"
    },
    "s3": {
        "s_id": 3,
        "s_name": "Commerce"
    },
  }
}

首先,我尝试了以下操作,但没有成功:

class AllSModel(BaseModel):
     s_id: int
     s_name: int

class StatesModel(BaseModel):
    all_s: AllSModel= None

然后从this SO post中引用

class JsonObject(BaseModel):
    __root__:  Dict[int, str]

class AssociatedObject(BaseModel):
    id: Optional[str]

class ObjectProperties(BaseModel):
    s_id: Optional[int]
    s_name: Optional[str]

class BaseObject(BaseModel):
    """
    Represents an object at the furthest depth
    of the nested structure
    """
    properties: ObjectProperties = ObjectProperties()

但是抛出以下错误:

pydantic.error_wrappers.ValidationError: 1 validation error for JsonObject
__root__
value is not a valid dict (type=type_error.dict)

我的def看起来是这样的:

def getResponseJSON():
  ----- more code ------  
  response = requests.post(decResponseURL,headers=headers, params=payload, verify=True)
  
  print(type(response))
  ''' Response is already posted in question'''
  ------ Error throws on below line ----
  b = JsonObject.parse_obj(response)
  print(b) 
  ---- if I turn response into json like below ---
  my_json_object = JsonObject.parse_obj(response.json())
  print(my_json_object)
  
  ---- then it throws following error ----
    line 183, in getResponseJSON
    my_json_object = JsonObject.parse_obj(response.json())
  File "/home/userpath/environments/my_env/lib/python3.10/site-packages/requests/models.py", line 975, in json
    raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)
requests.exceptions.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
 ----------------------------
  return "r_json"

我怀疑我的modal是否没有正确创建。请帮助纠正上述代码。

raogr8fs

raogr8fs1#

要解析特定的json,你可以使用这样的结构:

class AllSModel(BaseModel):
    s_id: int
    s_name: str

class Inter(BaseModel):
    __root__: dict[str, AllSModel]

class StatesModel(BaseModel):
    AllSeries: Inter = None

相关问题