@@ -373,8 +373,9 @@ print(Settings().model_dump())
373
373
374
374
### Disabling JSON parsing
375
375
376
- pydatnic-settings by default parses complex types from environment variables as JSON strings. If you want to disable
377
- this behavior for a field and parse the value by your own, you can annotate the field with ` NoDecode ` :
376
+ pydantic-settings by default parses complex types from environment variables as JSON strings. If you want to disable
377
+ this behavior for a field and parse the value in your own validator, you can annotate the field with
378
+ [ ` NoDecode ` ] ( ../api/pydantic_settings.md#pydantic_settings.NoDecode ) :
378
379
379
380
``` py
380
381
import os
@@ -430,13 +431,14 @@ print(Settings().model_dump())
430
431
# > {'numbers': [1, 2, 3]}
431
432
```
432
433
433
- You can force JSON parsing for a field by annotating it with ` ForceDecode ` . This will bypass
434
- the the ` enable_decoding ` config setting:
434
+ You can force JSON parsing for a field by annotating it with [ ` ForceDecode ` ] ( ../api/pydantic_settings.md#pydantic_settings.ForceDecode ) .
435
+ This will bypass the the ` enable_decoding ` config setting:
435
436
436
437
``` py
437
438
import os
438
439
from typing import List
439
440
441
+ from pydantic import field_validator
440
442
from typing_extensions import Annotated
441
443
442
444
from pydantic_settings import BaseSettings, ForceDecode, SettingsConfigDict
@@ -446,13 +448,23 @@ class Settings(BaseSettings):
446
448
model_config = SettingsConfigDict(enable_decoding = False )
447
449
448
450
numbers: Annotated[List[int ], ForceDecode]
451
+ numbers1: List[int ] # (1)!
452
+
453
+ @field_validator (' numbers1' , mode = ' before' )
454
+ @ classmethod
455
+ def decode_numbers1 (cls , v : str ) -> List[int ]:
456
+ return [int (x) for x in v.split(' ,' )]
449
457
450
458
451
459
os.environ[' numbers' ] = ' ["1","2","3"]'
460
+ os.environ[' numbers1' ] = ' 1,2,3'
452
461
print (Settings().model_dump())
453
- # > {'numbers': [1, 2, 3]}
462
+ # > {'numbers': [1, 2, 3], 'numbers1': [1, 2, 3] }
454
463
```
455
464
465
+ 1 . The ` numbers1 ` field is not annotated with ` ForceDecode ` , so it will not be parsed as JSON.
466
+ and we have to provide a custom validator to parse the value.
467
+
456
468
## Nested model default partial updates
457
469
458
470
By default, Pydantic settings does not allow partial updates to nested model default objects. This behavior can be
0 commit comments