python data_error ai_generated true

pydantic.errors.JsonError: 无效的 JSON

pydantic.errors.JsonError: Invalid JSON

ID: python/pydantic-json-load-error

其他格式: JSON · Markdown 中文 · English
80%修复率
82%置信度
0证据数
2024-05-12首次发现

版本兼容性

版本状态引入弃用备注
2.x active

根因分析

使用 Json 类型时,输入字符串不是有效的 JSON,导致解析失败。

English

When using Json type, the input string is not valid JSON, causing parsing failure.

generic

解决方案

  1. 90% 成功率
    Use Json type: data: Json
  2. 85% 成功率
    Validate with custom validator: @field_validator('data') def check_json(cls, v): json.loads(v); return v

无效尝试

常见但无效的做法:

  1. 60% 失败

    If input is already a dict, json.loads fails; Pydantic expects string.

  2. 80% 失败

    Empty string is not valid JSON.