One schema for python and typescript
Lets try to make one schema thats reusable across python and typescript. This is useful if one project needs to use both languages, this is something I do frequently as I use python for data-science coding and typescript for visualisation.
Lets define a simple json schema:
const schema = await FileAttachment('schema.json').json()
display(html`<pre>${JSON.stringify(schema, null, 2)}</pre>`)
We can then use zod and jsonschema in typescript to validate this object:
import { z } from "npm:zod";
import { validate } from "npm:jsonschema";
const schema = await FileAttachment('schema.json').json()
function validateWithJSONSchema(data: unknown) {
const result = validate(data, schema);
if (result.valid) {
display("Validation successful!");
} else {
display("Validation failed:", result.errors);
}
}
// Example usage
const data = {
name: "Eoin",
age: 30,
email: "eoin@example.com",
isActive: true,
tags: ["typescript", "zod"],
};
validateWithJSONSchema(data)
and the same thing in python
import json
import jsonschema
from jsonschema import validate
# Load the JSON schema
with open("schema.json", "r") as f:
schema = json.load(f)
# A utility to validate the data using the JSON schema
def validate_with_json_schema(data):
try:
validate(instance=data, schema=schema)
print("Validation successful!")
except jsonschema.exceptions.ValidationError as e:
print("Validation failed:", e.message)
# Example usage
data = {
"name": "Eoin",
"age": 30,
"email": "eoin@example.com",
"isActive": True,
"tags": ["python", "pydantic"],
}
validate_with_json_schema(data)