How to Convert GraphQL Query to JSON — Step-by-Step

Converting GraphQL queries to JSON is useful for caching, debugging, logging, and building middleware. This guide covers the most common approaches across different languages and tools.

What Does "GraphQL to JSON" Mean?

There are two distinct meanings:

  • Query → JSON structure — Parse the GraphQL query string and represent it as a JSON object (AST representation).
  • Query → JSON response — The result of executing a GraphQL query is always a JSON response. This is handled by the GraphQL runtime.

This article focuses on the first meaning: representing the query structure itself as JSON.

Using graphql-js (Node.js)

The graphql npm package includes a parse function that turns query strings into an AST. You can then serialize it:

JavaScript
import { parse, print } from 'graphql';

const query = `
  query getUser($id: ID!) {
    user(id: $id) {
      name
      email
      posts {
        title
      }
    }
  }
`;

const ast = parse(query);
// ast is a DocumentNode — it's already a JSON-compatible object
console.log(JSON.stringify(ast, null, 2));

Online Converter Approach

The fastest way to convert GraphQL queries to JSON is using the JSON to GraphQL Converter. Simply paste your GraphQL SDL on the left and get the JSON representation on the right — no code required.

Using Python (graphql-core)

The graphql-core library provides similar capabilities in Python:

Python
from graphql import parse, print_ast
import json

query = """
  query {
    user(id: 1) {
      name
      email
    }
  }
"""

ast = parse(query)
ast_dict = ast.to_dict()  # Convert to dictionary
print(json.dumps(ast_dict, indent=2))

Use Cases for GraphQL-to-JSON Conversion

  • Persisted queries — Store query representations in a database or cache.
  • API gateways — Transform and route GraphQL queries across microservices.
  • Testing — Generate test fixtures from real query structures.
  • Analytics — Log and analyze query patterns without parsing the raw string.