Skip to content

Commit

Permalink
Merge pull request #1 from KNMI/support_indent
Browse files Browse the repository at this point in the history
Support indentation of JSON
  • Loading branch information
PaulVanSchayck authored Feb 2, 2023
2 parents ec4850a + 9853fc5 commit dacca8c
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 12 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ c = Coverage(
"temperature": NdArray(axisNames=["x", "y", "t"], shape=[1, 1, 1], values=[42.0])
}
)
print(c.json(exclude_none=True))
print(c.json(exclude_none=True,indent=True))
```
Will print
```json
Expand Down
8 changes: 1 addition & 7 deletions example.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,9 @@
import datetime
import json

from covjson_pydantic.coverage import Coverage
from covjson_pydantic.domain import Domain
from covjson_pydantic.ndarray import NdArray


def pretty_print_json(json_str):
print(json.dumps(json.loads(json_str), indent=4))


c = Coverage(
domain=Domain(
domainType="PointSeries",
Expand All @@ -22,4 +16,4 @@ def pretty_print_json(json_str):
ranges={"temperature": NdArray(axisNames=["x", "y", "t"], shape=[1, 1, 1], values=[42.0])},
)

pretty_print_json(c.json(exclude_none=True))
print(c.json(exclude_none=True, indent=True))
13 changes: 9 additions & 4 deletions src/covjson_pydantic/base_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,16 @@
from pydantic import Extra


def orjson_dumps(v, *, default):
def orjson_dumps(v, *, default, indent=None, sort_keys=False):
options = orjson.OPT_NON_STR_KEYS | orjson.OPT_UTC_Z | orjson.OPT_NAIVE_UTC
if indent:
options |= orjson.OPT_INDENT_2

if sort_keys:
options |= orjson.OPT_SORT_KEYS

# orjson.dumps returns bytes, to match standard json.dumps we need to decode
return orjson.dumps(
v, default=default, option=orjson.OPT_NON_STR_KEYS | orjson.OPT_UTC_Z | orjson.OPT_NAIVE_UTC
).decode()
return orjson.dumps(v, default=default, option=options).decode()


class BaseModel(PydanticBaseModel):
Expand Down

0 comments on commit dacca8c

Please sign in to comment.