JSON to GraphQL Schema Generator
Infer GraphQL Schema Definition Language (SDL) types, queries, and scalar definitions directly from JSON data.
Unlike conventional calculator sites that send your financial numbers, payload data, or code snippets across remote web servers, Affi-Chain processes all mathematical derivations, algorithms, and data parsing 100% locally within your browser sandbox. No tracking cookies, no server-side retention, and zero transmission lag.
What is JSON to GraphQL Schema Generation?
JSON to GraphQL Schema Generation transforms sample JavaScript Object Notation (JSON) payloads into formal GraphQL Schema Definition Language (SDL) specifications. Developed by Meta (Facebook) in 2012 and open-sourced in 2015, GraphQL provides a strongly typed query language and runtime execution engine for APIs.
Unlike traditional REST endpoints—which return rigid, predetermined JSON payloads that frequently lead to network over-fetching (retrieving hundreds of unused database fields) or under-fetching (requiring cascading waterfall requests to resolve nested relationships)—GraphQL empowers client applications to request precisely the fields they need.
However, migrating legacy REST endpoints or microservice JSON responses to GraphQL requires defining comprehensive SDL type structures, establishing field nullability, and configuring root queries. Manually authoring SDL types for deep JSON objects is time-consuming and error-prone.
The Affi-Chain JSON to GraphQL Schema Generator inspects arbitrary JSON payloads, identifies data types and pattern heuristics (such as mapping string IDs to GraphQL's native ID scalar), recursively generates nested object types, and formats production-ready SDL with root Query fields directly in the browser with 0ms latency.
GraphQL SDL Type Inference & Mapping Matrix
The generator evaluates JSON tokens and maps them to standard GraphQL specifications:
| JSON Value / Structure | Sample Data | Inferred GraphQL SDL Type | Architectural Specification |
|---|---|---|---|
| String | "Jane Doe" | String | UTF-8 character sequence |
| Identifier String | "usr_98421" / "id": 10 | ID (or ID!) | Unique client-side cache normalization identifier |
| 32-Bit Integer | 42 | Int | Signed 32-bit integer (max: $2,147,483,647$) |
| Float / Decimal | 99.95 | Float | Signed double-precision fractional value |
| Boolean | true / false | Boolean | Boolean literal true or false |
| Array of Primitives | ["red", "blue"] | [String!] | Homogeneous sequence of non-null strings |
| Nested Object | {"city": "Austin"} | Address (Object Type) | Recursively generates independent SDL type block |
| Array of Objects | [{"sku": "A1"}, ...] | [Item!] | Enclosed list of nested object definitions |
| Null / Missing | null | Nullable (no ! modifier) | Permits null field returns |
Step-by-Step Practical Transformation Example
Let us examine how an e-commerce order JSON payload translates into clean GraphQL SDL.
Raw Input JSON:
{
"orderId": "ord_882910",
"totalAmount": 149.50,
"itemCount": 3,
"isPaid": true,
"customer": {
"id": "cst_48102",
"fullName": "Marcus Vance",
"email": "marcus@vance.io"
},
"tags": ["express", "fragile"]
}
Generated Production GraphQL SDL:
"""
Represents an individual customer identity profile.
"""
type Customer {
id: ID!
fullName: String!
email: String!
}
"""
Represents an e-commerce purchase order record.
"""
type Order {
orderId: ID!
totalAmount: Float!
itemCount: Int!
isPaid: Boolean!
customer: Customer!
tags: [String!]!
}
"""
Root operational queries for fetching data.
"""
type Query {
order(orderId: ID!): Order
orders: [Order!]!
}
Practical Code Implementation: In-Browser Schema Generator
Below is an in-browser JavaScript utility that recursively parses JSON trees and formats clean GraphQL SDL:
/**
* In-Browser JSON to GraphQL SDL Generator.
*/
class GraphQLSchemaGenerator {
constructor() {
this.types = new Map();
}
/**
* Generates complete SDL schema from raw JSON.
*/
generate(jsonString, rootTypeName = "Root") {
this.types.clear();
const data = JSON.parse(jsonString);
this.inferType(data, rootTypeName);
let sdl = "";
// Output all inferred sub-types
for (const [name, fields] of this.types.entries()) {
sdl += `type ${name} {\n`;
for (const [field, type] of Object.entries(fields)) {
sdl += ` ${field}: ${type}\n`;
}
sdl += `}\n\n`;
}
// Append Root Query definition
sdl += `type Query {\n`;
sdl += ` get${rootTypeName}: ${rootTypeName}\n`;
sdl += `}\n`;
return sdl.trim();
}
inferType(obj, typeName) {
if (typeof obj !== "object" || obj === null) return "String";
const fields = {};
for (const [key, value] of Object.entries(obj)) {
fields[key] = this.inferField(value, key);
}
this.types.set(typeName, fields);
return typeName;
}
inferField(value, fieldName) {
if (value === null || value === undefined) return "String";
if (typeof value === "string") {
if (/^(id|_id|orderId|userId|customerId)$/i.test(fieldName)) return "ID!";
return "String!";
}
if (typeof value === "number") {
return Number.isInteger(value) ? "Int!" : "Float!";
}
if (typeof value === "boolean") return "Boolean!";
if (Array.isArray(value)) {
if (value.length === 0) return "[String!]";
const sample = value[0];
if (typeof sample === "object" && sample !== null) {
const subTypeName = this.capitalize(fieldName.replace(/s$/, "")) + "Item";
this.inferType(sample, subTypeName);
return `[${subTypeName}!]!`;
}
return `[${this.inferField(sample, fieldName)}]!`;
}
if (typeof value === "object") {
const subTypeName = this.capitalize(fieldName);
return this.inferType(value, subTypeName) + "!";
}
return "String";
}
capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
}
// Verification Example:
const generator = new GraphQLSchemaGenerator();
const testPayload = JSON.stringify({ id: "101", title: "GraphQL Guide", views: 4500, published: true });
console.log(generator.generate(testPayload, "Article"));
Comparison Matrix: Schema Definition Paradigms
| Paradigm | Primary Protocol | Typing Model | Tooling / Ecosystem | Client Control |
|---|---|---|---|---|
| GraphQL SDL | HTTP / POST (Single Endpoint) | Strong (Scalars, Enums, Interfaces) | Apollo, Relay, URQL, Yoga | Total (Client dictates response shape) |
| OpenAPI / Swagger 3.0 | REST (Multiple Endpoints) | Schema-based (JSON Schema) | Swagger UI, Redoc, Postman | Low (Server dictates fixed endpoints) |
| JSON Schema | Data Validation | JSON Declarative Constraints | Ajv, Python jsonschema | N/A (Validation only) |
| TypeScript Interfaces | Compile-time only | Static JavaScript typing | tsc, IDE IntelliSense | N/A (Erased at runtime) |
Critical Edge Cases & Common Pitfalls
1. The GraphQL Int 32-Bit Overflow Trap
Under the official GraphQL specification, the built-in Int scalar is strictly a signed 32-bit integer:
$$-2,147,483,648 \le \text{Int} \le 2,147,483,647$$
If your JSON contains 64-bit database identifiers (like Twitter Snowflake IDs or PostgreSQL BIGINT numbers like 17283928192847192), the GraphQL execution engine will throw a runtime serialization error.
- Remediation: Model 64-bit numbers as
String,Float, or a customscalar BigInt.
2. Empty Array Inference Failure
When a sample JSON payload contains an empty array ("comments": []), the generator cannot inspect elements to determine the inner type. In production schema design, always supply representative sample payloads containing at least one populated item.
3. Circular Reference Modeling
If an object hierarchy contains cyclic relationships (e.g. Author has posts: [Post], and Post has author: Author), ensure type names match existing definitions rather than creating infinite type loops (AuthorPostAuthorPost...).