json schema python

Solutions on MaxInterview for json schema python by the best coders in the world

showing results for - "json schema python"
Violette
29 Jan 2020
1#Example usage of generating python code
2from jsonschemacodegen import python as pygen
3import json
4
5with open('schema.json') as fp:
6    generator = pygen.GeneratorFromSchema('output_dir')
7    generator.Generate(json.load(fp), 'Example', 'example')
8
9#using the generated code looks like
10
11import example
12import json
13
14jsonText = '["an example string in an array"]'
15
16obj = example.Example(json.loads(jsonText))
17
18print(json.dumps(obj, default=lambda x: x.Serializable()))
Alessandro
14 Jun 2017
1from datetime import datetime
2from typing import List, Optional
3from pydantic import BaseModel
4
5
6class User(BaseModel):
7    id: int
8    name = 'John Doe'
9    signup_ts: Optional[datetime] = None
10    friends: List[int] = []
11
12
13external_data = {
14    'id': '123',
15    'signup_ts': '2019-06-01 12:22',
16    'friends': [1, 2, '3'],
17}
18user = User(**external_data)
19print(user.id)
20#> 123
21print(repr(user.signup_ts))
22#> datetime.datetime(2019, 6, 1, 12, 22)
23print(user.friends)
24#> [1, 2, 3]
25print(user.dict())
26"""
27{
28    'id': 123,
29    'signup_ts': datetime.datetime(2019, 6, 1, 12, 22),
30    'friends': [1, 2, 3],
31    'name': 'John Doe',
32}
33"""