Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

document round_trip in Json type documentation #7137

Merged
merged 5 commits into from Aug 16, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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]"}
```