python config_error ai_generated true

pydantic_core._pydantic_core.ValidationError: 1 validation error for AppSettings database_urls Input should be a valid list [type=list_type, input_value='["db1","db2"]', input_type=str]

ID: python/pydantic-settings-env-parse-json

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
0Evidence
2024-11-22First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
2.x active — — —

Root Cause

pydantic-settings parses environment variables as strings by default. When a list-typed field is populated from an env var, the JSON string is not automatically decoded unless the field is annotated for complex parsing.

generic

中文

pydantic-settings 默认将环境变量作为字符串解析。当列表类型字段从环境变量填充时,JSON 字符串不会自动解码,除非字段被标注为复杂解析。

Workarounds

  1. 90% success
    from pydantic_settings import BaseSettings, SettingsConfigDict
    from pydantic import field_validator
    import json
    
    class AppSettings(BaseSettings):
        model_config = SettingsConfigDict(env_file='.env')
        database_urls: list[str]
    
        @field_validator('database_urls', mode='before')
        @classmethod
        def parse_json(cls, v):
            if isinstance(v, str):
                return json.loads(v)
            return v
  2. 75% success
    from pydantic_settings import BaseSettings, SettingsConfigDict
    from pydantic import Field
    
    class AppSettings(BaseSettings):
        database_urls: list[str] = Field(default_factory=list)

Dead Ends

Common approaches that don't work:

  1. 85% fail

    These settings control None handling and variable naming, not JSON decoding of complex types.

  2. 70% fail

    The validator receives the raw string before type coercion, so isinstance(v, list) is False and the error is re-raised.