JSON to GraphQL Schema Generator

Infer GraphQL Schema Definition Language (SDL) types, queries, and scalar definitions directly from JSON data.

4.9 / 5· 148 verified ratings
•
100% Client-Side Privacy
•
Verified 2026 Engine
Loading tool engine...
Frequently Used With:UUID / GUID Generator (v4 & v1) →Cron Expression Generator & Schedule Builder →Lorem Ipsum Placeholder Text Generator →HTML Entity Encoder & Decoder →
Institutional-Grade Accuracy & Client-Side Privacy Guarantee

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 / StructureSample DataInferred GraphQL SDL TypeArchitectural Specification
String"Jane Doe"StringUTF-8 character sequence
Identifier String"usr_98421" / "id": 10ID (or ID!)Unique client-side cache normalization identifier
32-Bit Integer42IntSigned 32-bit integer (max: $2,147,483,647$)
Float / Decimal99.95FloatSigned double-precision fractional value
Booleantrue / falseBooleanBoolean 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 / MissingnullNullable (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

ParadigmPrimary ProtocolTyping ModelTooling / EcosystemClient Control
GraphQL SDLHTTP / POST (Single Endpoint)Strong (Scalars, Enums, Interfaces)Apollo, Relay, URQL, YogaTotal (Client dictates response shape)
OpenAPI / Swagger 3.0REST (Multiple Endpoints)Schema-based (JSON Schema)Swagger UI, Redoc, PostmanLow (Server dictates fixed endpoints)
JSON SchemaData ValidationJSON Declarative ConstraintsAjv, Python jsonschemaN/A (Validation only)
TypeScript InterfacesCompile-time onlyStatic JavaScript typingtsc, IDE IntelliSenseN/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 custom scalar 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...).

Frequently Asked Questions

How are nested JSON objects represented in GraphQL?
Nested objects are automatically extracted into distinct named GraphQL object types and linked to the parent schema.

Explore Related Utilities