Skip to content

Commit

Permalink
document round_trip in Json type documentation (#7137)
Browse files Browse the repository at this point in the history
Co-authored-by: David Montague <35119617+dmontagu@users.noreply.github.com>
  • Loading branch information
jc-louis and dmontagu committed Aug 16, 2023
1 parent 0d4b77b commit f2fd9b2
Showing 1 changed file with 16 additions and 4 deletions.
20 changes: 16 additions & 4 deletions docs/usage/types/json.md
@@ -1,11 +1,10 @@
`Json`
: a special type wrapper which loads JSON before parsing

You can use `Json` data type to make Pydantic first load a raw JSON string.
It can also optionally be used to parse the loaded object into another type base on
the type `Json` is parameterised with:
You can use the `Json` data type to make Pydantic first load a raw JSON string before
validating the loaded data into the parametrized type:

```py
```py group='json'
from typing import Any, List

from pydantic import BaseModel, Json, ValidationError
Expand All @@ -23,6 +22,7 @@ print(AnyJsonModel(json_obj='{"b": 1}'))
#> json_obj={'b': 1}
print(ConstrainedJsonModel(json_obj='[1, 2, 3]'))
#> json_obj=[1, 2, 3]

try:
ConstrainedJsonModel(json_obj=12)
except ValidationError as e:
Expand Down Expand Up @@ -55,3 +55,15 @@ except ValidationError as e:
Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='b', input_type=str]
"""
```

When you dump the model using `model_dump` or `model_dump_json`, the dumped value will be the result of validation,
not the original JSON string. However, you can use the argument `round_trip=True` to get the original JSON string back:

```py group='json'
print(ConstrainedJsonModel(json_obj='[1, 2, 3]').model_dump_json())
#> {"json_obj":[1,2,3]}
print(
ConstrainedJsonModel(json_obj='[1, 2, 3]').model_dump_json(round_trip=True)
)
#> {"json_obj":"[1,2,3]"}
```

0 comments on commit f2fd9b2

Please sign in to comment.