Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
# Changelog

## 10.1.0 (unreleased)

Features:

- Allow `default` for `env.json` to be a `dict` or `list` ([#240](https://github.com/sloria/environs/pull/240)).
Thanks [tomgrin10](https://github.com/tomgrin10) and [bvanelli](https://github.com/bvanelli) for the PRs.

## 10.0.0 (2023-12-15)

Features:
Expand Down
9 changes: 7 additions & 2 deletions environs/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -231,9 +231,14 @@ def _preprocess_dict(
}


def _preprocess_json(value: str, **kwargs):
def _preprocess_json(value: typing.Union[str, typing.Mapping, typing.List], **kwargs):
try:
return pyjson.loads(value)
if isinstance(value, str):
return pyjson.loads(value)
elif isinstance(value, dict) or isinstance(value, list) or value is None:
return value
else:
raise ma.ValidationError("Not valid JSON.")
except pyjson.JSONDecodeError as error:
raise ma.ValidationError("Not valid JSON.") from error

Expand Down
7 changes: 7 additions & 0 deletions tests/test_environs.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,13 @@ def test_invalid_json_raises_error(self, set_env, env):
env.json("JSON")
assert "Not valid JSON." in exc.value.args[0]

def test_json_default(self, set_env, env):
assert env.json("JSON", {"foo": "bar"}) == {"foo": "bar"}
assert env.json("JSON", ["foo", "bar"]) == ["foo", "bar"]
with pytest.raises(environs.EnvError) as exc:
env.json("JSON", int) # a builtin is not a valid json
assert "Not valid JSON." in exc.value.args[0]

def test_datetime_cast(self, set_env, env):
dtime = dt.datetime.utcnow()
set_env({"DTIME": dtime.isoformat()})
Expand Down