# JSON Schema Auto-Generator (Infer from Samples) (`gochujang/json-schema-generator`) Actor

Provide one or more JSON samples (inline or from URLs) and get an inferred JSON Schema (Draft 7 / 2020-12) describing their shape. Bootstrap API validators, Apify input schemas, BigQuery / DuckDB schemas. Powered by genson. $0.01 per inference.

- **URL**: https://apify.com/gochujang/json-schema-generator.md
- **Developed by:** [Hojun Lee](https://apify.com/gochujang) (community)
- **Categories:** Developer tools
- **Features:** Limited permissions
- **Stats:** 3 total users, 2 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $10.00 / 1,000 schema generateds

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## JSON Schema Auto-Generator

> Provide one or more JSON samples (inline or from URLs) and get an inferred JSON Schema (**Draft 7 / 2020-12**) describing their shape. Bootstrap API validators, Apify input schemas, BigQuery / DuckDB schemas. Powered by **genson**. **$0.01 per inference.**

***

### ⚡ Run in 30 seconds

Click **Start** with default settings — takes the sample JSON object and returns a complete JSON Schema (Draft 7) inferred from its structure, including property types, required fields, and nested object definitions, ready to paste into a validator or API spec.

***

### Input Parameters

| Parameter | Type | Default | Description |
|---|---|---|---|
| `samples` | array | `[]` | Array of JSON objects to merge into one inferred schema. |
| `sample` | object | `{}` | Used when 'samples' is empty. |
| `sampleUrls` | array | `[]` | Fetch each URL as JSON and add to the sample set. |
| `schemaUri` | string | `https://json-schema.org/draft/2020-12/schema` | Which JSON Schema version to target. |
| `schemaTitle` | string | ``| Embed in the generated schema's 'title' field. |
| `schemaDescription` | string |`` | Embed in the generated schema's 'description' field. |
| `requireAll` | boolean | `true` | If false, drop the 'required' array. |
| `userAgent` | string | \`\` | Custom UA when fetching sampleUrls. |

***

### Why this exists

You hit an API that returns JSON. You want to validate downstream payloads, store them in a typed table, or auto-generate TypeScript types — but writing a JSON Schema by hand from 30 nested fields is tedious.

This actor takes one or more sample payloads and **infers** the schema. The result is a real, RFC-compliant JSON Schema you can drop into Ajv, BigQuery, OpenAPI, Apify input_schema.json, etc.

***

### What you get

```json
{
  "_type": "schema",
  "samples_used": 3,
  "schema_uri": "https://json-schema.org/draft/2020-12/schema",
  "title": "User",
  "inferred_schema": {
    "$schema": "https://json-schema.org/draft/2020-12/schema",
    "type": "object",
    "title": "User",
    "additionalProperties": false,
    "properties": {
      "id": {"type": "integer"},
      "email": {"type": "string"},
      "tags": {"type": "array", "items": {"type": "string"}},
      "meta": {
        "type": "object",
        "properties": {
          "created": {"type": "string"},
          "verified": {"type": "boolean"}
        },
        "required": ["created"]
      }
    },
    "required": ["id", "email"]
  },
  "schema_str": "<pretty-printed schema as text>",
  "top_level_keys": ["id", "email", "tags", "meta"],
  "top_level_required": ["id", "email"]
}
```

The full schema is also saved as `inferred_schema.json` in the run's KeyValueStore — easy to download.

***

### Quick start

#### Single sample

```json
{
  "sample": {
    "id": 1,
    "email": "test@example.com",
    "tags": ["a", "b"],
    "meta": {"created": "2024-01-01", "verified": true}
  }
}
```

#### Merge multiple samples (recommended — better union types)

```json
{
  "samples": [
    {"id": 1, "name": "foo"},
    {"id": 2, "name": "bar", "deleted_at": "2024-01-01"},
    {"id": 3, "name": "baz", "deleted_at": null}
  ]
}
```

#### Fetch samples from URLs

```json
{
  "sampleUrls": [
    "https://api.github.com/users/torvalds",
    "https://api.github.com/users/octocat"
  ],
  "schemaTitle": "GitHub User",
  "schemaUri": "https://json-schema.org/draft/2020-12/schema"
}
```

***

### Pricing

**Pay-Per-Event**: `$0.01 per schema inference.`

Cheap, fixed-cost. Run as many times as you want during API evolution.

***

### Use cases

1. **Bootstrap Apify `input_schema.json`** — Use it on a sample input, drop the schema into your actor's `.actor/input_schema.json`
2. **REST API validators** — Generate Ajv-compatible schemas from real production responses
3. **BigQuery / DuckDB tables** — Convert JSON Schema → DDL with a follow-up tool
4. **OpenAPI** — Drop schemas under `components.schemas` for type-safe SDK generation
5. **Comparison** — Run on prod vs staging payloads; diff the schemas to spot drift

***

### Output details

- `inferred_schema` — the schema as a JS object (use this in code)
- `schema_str` — pretty-printed text (paste into a file)
- `top_level_keys` — convenience for renaming / sorting fields
- `additionalProperties: false` is set by default for objects (strict mode). To allow extras, remove it before using the schema.

***

### Limitations / gotchas

- **More samples = better schema.** A single sample can't tell required vs optional. Pass 5-10 samples covering all common cases.
- **`null` handling** — When a field is sometimes null, the inferred type becomes `["string", "null"]` (or similar). This is correct JSON Schema but some tools (e.g. old Avro) don't like unions.
- **Format detection** — `genson` doesn't infer `format: date-time` etc. by default. For format-aware generation, post-process manually.

***

### Engine

- **genson** v1.2+ — the reference Python implementation. Well-maintained, used in many data pipelines.

***

### Related actors (same author)

- [Web Page → Markdown Converter](https://apify.com/gochujang/web-to-markdown)
- [HTML Metadata Extractor](https://apify.com/gochujang/html-metadata-extractor)
- [PDF Text Extractor](https://apify.com/gochujang/pdf-text-extractor)
- [Sitemap URL Discovery](https://apify.com/gochujang/sitemap-url-discovery)

***

### Feedback

A short review helps developers find it: [Leave a review on Apify Store](https://apify.com/gochujang/json-schema-generator#reviews)

***

**Keywords:** JSON Schema generator, infer schema from JSON, JSON Schema Draft 7, JSON Schema 2020-12, TypeScript interface generator, OpenAPI schema generator, Apify input schema, BigQuery schema inference, DuckDB schema, Ajv validator bootstrap, API payload schema, genson Python, JSON type inference, schema from URL

# Actor input Schema

## `samples` (type: `array`):

Array of JSON objects to merge into one inferred schema.

## `sample` (type: `object`):

Used when 'samples' is empty.

## `sourceUrl` (type: `string`):

Fetch a single JSON URL and use it as the sample. Content-Type must be application/json or text/plain.

## `sampleUrls` (type: `array`):

Fetch each URL as JSON and merge all into the sample set.

## `schemaVersion` (type: `string`):

JSON Schema version to target. Overrides schemaUri when set.

## `schemaUri` (type: `string`):

Custom $schema URI. Ignored when schemaVersion is set.

## `schemaTitle` (type: `string`):

Embed in the generated schema's 'title' field. Also used as the TypeScript interface / OpenAPI component name.

## `schemaDescription` (type: `string`):

Embed in the generated schema's 'description' field.

## `requireAll` (type: `boolean`):

If false, drop the 'required' array so every field is optional.

## `generateTypescript` (type: `boolean`):

When enabled, output includes a 'typescript_types' field with an exported TypeScript interface / type alias derived from the schema.

## `generateOpenApi` (type: `boolean`):

When enabled, output includes an 'openapi_component' field in OpenAPI 3.0 components/schemas format.

## `userAgent` (type: `string`):

Custom User-Agent header when fetching sourceUrl or sampleUrls.

## Actor input object example

```json
{
  "samples": [],
  "sample": {},
  "sourceUrl": "",
  "sampleUrls": [],
  "schemaVersion": "draft-2020-12",
  "schemaUri": "",
  "schemaTitle": "",
  "schemaDescription": "",
  "requireAll": true,
  "generateTypescript": false,
  "generateOpenApi": false,
  "userAgent": ""
}
```

# Actor output Schema

## `dataset` (type: `string`):

No description

## `summary` (type: `string`):

No description

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {};

// Run the Actor and wait for it to finish
const run = await client.actor("gochujang/json-schema-generator").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {}

# Run the Actor and wait for it to finish
run = client.actor("gochujang/json-schema-generator").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{}' |
apify call gochujang/json-schema-generator --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,gochujang/json-schema-generator"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/tcYkvhsk4OrPJVbhi/builds/wu8JLlNGLtkTXjl7Y/openapi.json
