So far the closest thing I've been able to find is warlock, which advertises this workflow:

Build your schema

>>> schema = {
    'name': 'Country',
    'properties': {
        'name': {'type': 'string'},
        'abbreviation': {'type': 'string'},
    },
    'additionalProperties': False,
}

Create a model

>>> import warlock
>>> Country = warlock.model_factory(schema)

Create an object using your model

>>> sweden = Country(name='Sweden', abbreviation='SE')

However, it's not quite that easy. The objects that Warlock produces lack much in the way of introspectible goodies. And if it supports nested dicts at initialization, I was unable to figure out how to make them work.

To give a little background, the problem that I was working on was how to take Chrome's JSONSchema API and produce a tree of request generators and response handlers. Warlock doesn't seem too far off the mark, the only downside is that meta-classes in Python can't really be turned into 'code'.

Other useful modules to look for:

  • jsonschema - (which Warlock is built on top of)
  • valideer - similar to jsonschema but with a worse name.
  • bunch - An interesting structure builder thats half-way between a dotdict and construct

If you end up finding a good one-stop solution for this please follow up your question - I'd love to find one. I poured through github, pypi, googlecode, sourceforge, etc.. And just couldn't find anything really sexy.

For lack of any pre-made solutions, I'll probably cobble together something with Warlock myself. So if I beat you to it, I'll update my answer. :p

Answer from synthesizerpatel on Stack Overflow
๐ŸŒ
PyPI
pypi.org โ€บ project โ€บ json-schema-codegen
json-schema-codegen ยท PyPI
See example_usage.py for a more elaborate example on generating C++ code. import jsonschemacodegen.cpp as cpp simpleResolver = cpp.SimpleResolver() output_dir = "/tmp" generator = cpp.GeneratorFromSchema(src_output_dir=output_dir, header_output_dir=output_dir, resolver=simpleResolver, namespace=[], src_usings=[]) sampleSchema = {"type": "string"} generator.Generate(sampleSchema, 'Example', 'example') A Python3 class is generated for each schema node; the class encapsulating the data described by the schema.
      ยป pip install json-schema-codegen
    
Published ย  May 01, 2023
Version ย  0.6.3
๐ŸŒ
PyPI
pypi.org โ€บ project โ€บ genson
genson ยท PyPI
Generate a schema and convert it directly to serialized JSON. ... Check for equality with another SchemaBuilder object. ... You can pass one schema directly to another to merge them.
      ยป pip install genson
    
Published ย  May 15, 2024
Version ย  1.3.0
Discussions

validation - Tool to generate JSON schema from JSON data - Stack Overflow
This example has been coded manually, so it may have errors. Is there any tool out there which could help me with the conversion JSON -> JSON schema? ... In the example provided, I would say it is clear that we have a dictionary (python terminology), with key-value pairs, where the values happen ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Python JSON dummy data generation from JSON schema - Stack Overflow
I am looking for a python library in which I can feed in my JSON schema and it generates dummy data. I have worked with a similar library in javascript dummy-json. Does anyone about a library which... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Automatic fake JSON data creation from schema
I'm new to Python. Is this just like "Lorem Ipsum" filler content to make JSON's with to test software pipelines with? More on reddit.com
๐ŸŒ r/Python
10
7
January 6, 2021
Generating JSON Schemas Using Typed Objects (Similar to Python "Pydantic")
Curious what you find More on reddit.com
๐ŸŒ r/ruby
12
5
August 6, 2024
Top answer
1 of 5
39

So far the closest thing I've been able to find is warlock, which advertises this workflow:

Build your schema

>>> schema = {
    'name': 'Country',
    'properties': {
        'name': {'type': 'string'},
        'abbreviation': {'type': 'string'},
    },
    'additionalProperties': False,
}

Create a model

>>> import warlock
>>> Country = warlock.model_factory(schema)

Create an object using your model

>>> sweden = Country(name='Sweden', abbreviation='SE')

However, it's not quite that easy. The objects that Warlock produces lack much in the way of introspectible goodies. And if it supports nested dicts at initialization, I was unable to figure out how to make them work.

To give a little background, the problem that I was working on was how to take Chrome's JSONSchema API and produce a tree of request generators and response handlers. Warlock doesn't seem too far off the mark, the only downside is that meta-classes in Python can't really be turned into 'code'.

Other useful modules to look for:

  • jsonschema - (which Warlock is built on top of)
  • valideer - similar to jsonschema but with a worse name.
  • bunch - An interesting structure builder thats half-way between a dotdict and construct

If you end up finding a good one-stop solution for this please follow up your question - I'd love to find one. I poured through github, pypi, googlecode, sourceforge, etc.. And just couldn't find anything really sexy.

For lack of any pre-made solutions, I'll probably cobble together something with Warlock myself. So if I beat you to it, I'll update my answer. :p

2 of 5
28

python-jsonschema-objects is an alternative to warlock, build on top of jsonschema

python-jsonschema-objects provides an automatic class-based binding to JSON schemas for use in python.

Usage:

Sample Json Schema

schema = '''{
    "title": "Example Schema",
    "type": "object",
    "properties": {
        "firstName": {
            "type": "string"
        },
        "lastName": {
            "type": "string"
        },
        "age": {
            "description": "Age in years",
            "type": "integer",
            "minimum": 0
        },
        "dogs": {
            "type": "array",
            "items": {"type": "string"},
            "maxItems": 4
        },
        "gender": {
            "type": "string",
            "enum": ["male", "female"]
        },
        "deceased": {
            "enum": ["yes", "no", 1, 0, "true", "false"]
            }
    },
    "required": ["firstName", "lastName"]
} '''

Converting the schema object to class

 import python_jsonschema_objects as pjs
 import json
 schema = json.loads(schema)   
 builder = pjs.ObjectBuilder(schema)   
 ns = builder.build_classes()   
 Person = ns.ExampleSchema   
 james = Person(firstName="James", lastName="Bond")   
 james.lastName  
  u'Bond'  james      
 example_schema lastName=Bond age=None firstName=James  

Validation :

james.age = -2 python_jsonschema_objects.validators.ValidationError: -2 was less or equal to than 0

But problem is , it is still using draft4validation while jsonschema has moved over draft4validation , i filed an issue on the repo regarding this . Unless you are using old version of jsonschema , the above package will work as shown.

๐ŸŒ
JSON Type Definition
jsontypedef.com โ€บ docs โ€บ python-codegen
Generating Python from JSON Typedef schemas
jtd-codegen schemas/user.jtd.json --python-out src/user ... ๐Ÿ“ Writing Python code to: src/user ๐Ÿ“ฆ Generated Python code. ๐Ÿ“ฆ Root schema converted into type: User ยท And you should see code along these lines in src/user/__init.py__: from ...
๐ŸŒ
GitHub
github.com โ€บ altair-viz โ€บ schemapi
GitHub - altair-viz/schemapi: Auto-generate Python APIs from JSON schema specifications
July 23, 2020 - Auto-generate Python APIs from JSON schema specifications - altair-viz/schemapi
Starred by 79 users
Forked by 12 users
Languages ย  Python 82.4% | Jupyter Notebook 17.4% | Makefile 0.2% | Python 82.4% | Jupyter Notebook 17.4% | Makefile 0.2%
๐ŸŒ
GitHub
github.com โ€บ microsoft โ€บ jschema-to-python
GitHub - microsoft/jschema-to-python: Generate source code for a set of Python classes from a JSON schema.
Generate Python classes from a JSON schema. python -m jschema_to_python [-h] -s SCHEMA_PATH -o OUTPUT_DIRECTORY [-m MODULE_NAME] -r ROOT_CLASS_NAME [-g HINTS_FILE_PATH] [-f] [-v] Generate source code for a set of Python classes from a JSON schema.
Starred by 38 users
Forked by 18 users
Languages ย  Python 100.0% | Python 100.0%
Find elsewhere
๐ŸŒ
GitHub
github.com โ€บ expobrain โ€บ json-schema-codegen
GitHub - expobrain/json-schema-codegen: Generate code from JSON schema files
The generation of Python 3's code with Marshmallow support is integrated into the tool so it needs just a single invocation: json_codegen --language python3+marshmallow --output <output_py_file> <json-schema>
Starred by 40 users
Forked by 5 users
Languages ย  JavaScript 91.7% | Python 8.3% | JavaScript 91.7% | Python 8.3%
๐ŸŒ
Reddit
reddit.com โ€บ r/python โ€บ automatic fake json data creation from schema
r/Python on Reddit: Automatic fake JSON data creation from schema
January 6, 2021 -

https://github.com/ghandic/jsf

Use jsf along with fake data generators to provide consistent and meaningful fake data for your system.

Main Features

  • Provides out of the box data generation from any JSON schema ๐Ÿ“ฆ

  • Extendable custom data providers using any lambda functions ๐Ÿ”—

  • Multi level state for dependant data (eg multiple objects sharing value, such as children with same surname) ๐Ÿค“

  • Inbuilt validation of fake JSON produced โœ…

  • In memory conversion from JSON Schema to Pydantic Models with generated examples ๐Ÿคฏ

  • Seamless integration with FastAPI ๐Ÿš€

Installation

$ pip install jsf

---> 100%

Usage

Basic ๐Ÿ˜Š

from jsf import JSF

faker = JSF(
    {
        "type": "object",
        "properties": {
            "name": {"type": "string", "$provider": "faker.name"},
            "email": {"type": "string", "$provider": "faker.email"},
        },
        "required": ["name", "email"],
    }
)

fake_json = faker.generate()

Results in ...

{
    'name': 'Jesse Phillips', 
    'email': 'xroberson@hotmail.com'
}

From JSON file ๐Ÿ“

from jsf import JSF

faker = JSF.from_json("demo-schema.json")
fake_json = faker.generate()

<details markdown="1"> <summary>Or run stright from the <code>commandline</code>...</summary>

Native install

jsf --schema src/tests/data/custom.json --instance wow.json

Docker

docker run -v $PWD:/data challisa/jsf jsf --schema /data/custom.json --instance /data/example.json

</details>

FastAPI Integration ๐Ÿš€

Create a file main.py with:

from jsf import JSF
from fastapi import FastAPI

app = FastAPI(docs_url="/")
generator = JSF.from_json("custom.json")


@app.get("/generate", response_model=generator.pydantic())
def read_root():
    return generator.generate()

Run the server with:

<div class="termy">

$ uvicorn main:app --reload

INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [28720]
INFO:     Started server process [28722]
INFO:     Waiting for application startup.
INFO:     Application startup complete.

Navigate to http://127.0.0.1:8000 and check out your endpoint. Notice the following are all automatically created:

  • Schema with descriptions and examples

  • Example response

  • Data generation by clicking "try it out"

๐ŸŒ
Snyk
snyk.io โ€บ advisor โ€บ python packages โ€บ json-schema-codegen
json-schema-codegen - Python Package Health Analysis | Snyk
We found a way for you to contribute to the project! Looks like json-schema-codegen is missing a Code of Conduct. ... This python library consumes JSON-Schema and generates C++ or Python code.
๐ŸŒ
GitHub
github.com โ€บ python-jsonschema โ€บ hypothesis-jsonschema
GitHub - python-jsonschema/hypothesis-jsonschema: Tools to generate test data from JSON schemata with Hypothesis ยท GitHub
Custom formats are ignored # by default, but you can pass custom strategies for them - e.g. custom_formats={"card": st.sampled_from(EXAMPLE_CARD_NUMBERS)}, ) ) def test_card_numbers(value): assert isinstance(value, str) assert re.match(r"^\d{4} \d{4} \d{4} \d{4}$", value) @given(from_schema({}, allow_x00=False, codec="utf-8").map(json.dumps)) def test_card_numbers(payload): assert isinstance(payload, str) assert "\0" not in payload # use allow_x00=False to exclude null characters # If you want to restrict generated strings characters which are valid in # a specific character encoding, you can do that with the `codec=` argument.
Starred by 279 users
Forked by 36 users
Languages ย  Python
๐ŸŒ
Apidog
apidog.com โ€บ articles โ€บ how-to-create-json-schema-python
How to Create JSON Schema in Python
October 20, 2023 - Python offers several libraries and tools for working with JSON schemas, but one of the most popular choices is the "jsonschema" library. In this guide, we will use this library to create JSON schemas in Python.
๐ŸŒ
Pydantic
docs.pydantic.dev โ€บ latest โ€บ concepts โ€บ json_schema
JSON Schema - Pydantic Validation
Note that this overrides the whole JSON Schema generation process for the field (in the following example, the 'type' also needs to be provided). import json from typing import Annotated from pydantic import BaseModel, WithJsonSchema MyInt = Annotated[ int, WithJsonSchema({'type': 'integer', 'examples': [1, 0, -1]}), ] class Model(BaseModel): a: MyInt print(json.dumps(Model.model_json_schema(), indent=2))
๐ŸŒ
GitHub
github.com โ€บ sbrunner โ€บ jsonschema-gentypes
GitHub - sbrunner/jsonschema-gentypes: Tool to generate Python types based on TypedDict from a JSON Schema
headers: > # Automatically generated file from a JSON schema # Used to correctly format the generated file callbacks: - - black - - isort generate: - # JSON schema file path source: jsonschema_gentypes/schema.json # Python file path destination: jsonschema_gentypes/configuration.py # The name of the root element root_name: Config # Argument passed to the API api_arguments: additional_properties: Only explicit # Rename an element name_mapping: {} # The minimum Python version that the code should support.
Starred by 48 users
Forked by 16 users
Languages ย  Python 99.7% | Makefile 0.3% | Python 99.7% | Makefile 0.3%
๐ŸŒ
GitHub
github.com โ€บ koxudaxi โ€บ datamodel-code-generator
GitHub - koxudaxi/datamodel-code-generator: Python data model generator (Pydantic, dataclasses, TypedDict, msgspec) from OpenAPI, JSON Schema, GraphQL, and raw data (JSON/YAML/CSV). ยท GitHub
๐Ÿ“„ Converts OpenAPI 3, JSON Schema, GraphQL, and raw data (JSON/YAML/CSV) into Python models ยท ๐Ÿ Generates from existing Python types (Pydantic, dataclass, TypedDict) via --input-model ยท ๐ŸŽฏ Generates Pydantic v2, Pydantic v2 dataclass, dataclasses, TypedDict, or msgspec output ยท ๐Ÿ”— Handles complex schemas: $ref, allOf, oneOf, anyOf, enums, and nested types ยท โœ… Produces type-safe, validated code ready for your IDE and type checker
Starred by 3.8K users
Forked by 430 users
Languages ย  Python
๐ŸŒ
DEV Community
dev.to โ€บ stefanalfbo โ€บ python-json-schema-3o7n
Python JSON schema - DEV Community
May 9, 2024 - import pytest from rest_framework.test import APIClient from django.contrib.auth.models import User @pytest.mark.django_db def test_get_user(): # Create a user _ = User.objects.create_user(username="test-user", email="test-user@example.com") client = APIClient() response = client.get('/users/1/') assert response.status_code == 200 ยท I have changed one thing in the UserViewSet to get this to work, and that is to change the permission_classes to permission.AllowAny, just for demo purposes. We can now extend our test and use the jsonschema library. In the example below is a test that is validating that the response from our API is fulfilling our contract (JSON schema) by using the validate function.
๐ŸŒ
LinkedIn
linkedin.com โ€บ pulse โ€บ python-code-generate-payload-from-json-schema-bhanu-akaveeti
Python code to generate payload from JSON schema
February 26, 2022 - This python code generates payload (with random values) from a generic JSON schema. https://github.
๐ŸŒ
jsonschema
python-jsonschema.readthedocs.io
jsonschema 4.26.0 documentation
PyPI version Supported Python versions Build status ReadTheDocs status pre-commit.ci status Zenodo DOI jsonschema is an implementation of the JSON Schema specification for Python. It can also be us...
๐ŸŒ
Unstructured
docs.unstructured.io โ€บ api-reference โ€บ partition โ€บ generate-schema
Generate a JSON schema for a file - Unstructured
Set LOCAL_FILE_OUTPUT_PATH to the local path to the output (target) JSON schema file to be generated. Add the following Python code file to your project: ... import os, json from genson import SchemaBuilder def json_schema_from_file( ...