This project provides a JavaScript utility that converts JSON Schema definitions into Python functions.
Each generated Python function creates a dictionary (dict) from schema properties, handling both required and optional fields.
The script iterates over schema.definitions and:
- Creates a Python function for each definition.
- Initializes variables for each property.
- Builds a dictionary (
data) with keys corresponding to schema properties. - Handles required vs. optional properties:
- Required: always included in the dictionary.
- Optional: only included if a value is provided.
- Prints and returns the generated dictionary(in the browser console).
- Downloads the result as
json_to_dict.py.
-
camelToSnakecase(camelCase)
Converts camelCase names from the schema into Pythonicsnake_case. -
startFunction(currentDefinition)
Creates a new Python function header for the current schema definition. -
addVariable(currentProperty)
Adds placeholder variable assignments (property = "") for each property. -
addDict(currentProperty, requiredArray)
Adds each property into thedatadictionary, respecting required/optional rules. -
finishFunction(currentDefinition)
Combines the generated code and appends it to thepythonString. -
downloadPythonFile(filename, content)
Triggers download of the generated Python file.
- Define your JSON Schema in a variable called
schema(must includedefinitions). - Run the script in a browser environment (Node.js version would require minor adjustments).
- After processing, a Python file
json_to_dict.pywill be downloaded containing the generated functions.
For a schema definition like:
"User": {
"required": ["id"],
"properties": {
"id": {"type": "string"},
"name": {"type": "string"}
}
}The generated Python function will look like:
def user(client_data):
id = ""
name = ""
data = {}
data["id"] = id
if name:
data["name"] = name
print(data)
return data
user('')