Skip to content

Instantly share code, notes, and snippets.

@mitsuse
Last active March 28, 2018 01:52
Show Gist options
  • Save mitsuse/7905bf49c54cf3f6939cb0e057fa764f to your computer and use it in GitHub Desktop.
Save mitsuse/7905bf49c54cf3f6939cb0e057fa764f to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
from typing import NamedTuple
import typedjson
class NameJson(NamedTuple):
first: str
last: str
class UserJson(NamedTuple):
id: str
age: int
name: NameJson
json = {'id': 'test-user', 'age': 20, 'name': {'first': 'foo', 'last': 'bar'}}
invalid_json = {'age': 20, 'name': {'first': 'foo', 'last': 'bar'}}
print(typedjson.decode(UserJson, json)) # UserJson(id='test-user', age=20, name=NameJson(first='foo', last='bar'))
print(typedjson.decode(UserJson, invalid_json)) # DecodingError(path=('id',))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment