Answers for "json schema python"

2

generate schema from json python

#Example usage of generating python code
from jsonschemacodegen import python as pygen
import json

with open('schema.json') as fp:
    generator = pygen.GeneratorFromSchema('output_dir')
    generator.Generate(json.load(fp), 'Example', 'example')

#using the generated code looks like

import example
import json

jsonText = '["an example string in an array"]'

obj = example.Example(json.loads(jsonText))

print(json.dumps(obj, default=lambda x: x.Serializable()))
Posted by: Guest on May-31-2021
1

json schema python

from datetime import datetime
from typing import List, Optional
from pydantic import BaseModel


class User(BaseModel):
    id: int
    name = 'John Doe'
    signup_ts: Optional[datetime] = None
    friends: List[int] = []


external_data = {
    'id': '123',
    'signup_ts': '2019-06-01 12:22',
    'friends': [1, 2, '3'],
}
user = User(**external_data)
print(user.id)
#> 123
print(repr(user.signup_ts))
#> datetime.datetime(2019, 6, 1, 12, 22)
print(user.friends)
#> [1, 2, 3]
print(user.dict())
"""
{
    'id': 123,
    'signup_ts': datetime.datetime(2019, 6, 1, 12, 22),
    'friends': [1, 2, 3],
    'name': 'John Doe',
}
"""
Posted by: Guest on September-26-2021

Python Answers by Framework

Browse Popular Code Answers by Language