How to Generate GraphQL Types from JSON Automatically
Manually writing GraphQL types for existing JSON data is tedious and error-prone. This guide covers automated approaches — from online tools to CLI scripts — so you can generate SDL in seconds.
1. Online Converter (Fastest)
The quickest way is using a browser-based tool. Our JSON to GraphQL Converter runs entirely client-side — paste JSON on the left and get SDL on the right instantly. No sign-up, no server upload.
2. Using Our Converter Tool
Visit the JSON to GraphQL Converter, paste your JSON, and the SDL appears instantly. Features include:
- Automatic type name generation (PascalCase from JSON keys).
- Recursive nested object handling.
- Array item type inference.
- Non-null toggle for required fields.
- Customizable root query wrapper name.
- One-click copy to clipboard.
3. Node.js Script
For automated pipelines, here's a simple approach using Node.js:
function toPascalCase(str) {
return str.replace(/(^\w|_\w)/g, m =>
m.replace('_', '').toUpperCase()
);
}
function inferType(value, name) {
if (Array.isArray(value)) {
const itemType = value.length > 0
? inferType(value[0], name + 'Item')
: 'String';
return '[' + itemType + ']';
}
if (typeof value === 'object' && value !== null) {
return generateType(name, value);
}
const map = {
string: 'String',
number: Number.isInteger(value) ? 'Int' : 'Float',
boolean: 'Boolean',
};
return map[typeof value] || 'String';
}
function generateType(name, obj) {
const fields = Object.entries(obj).map(([key, val]) => {
const ft = inferType(val, toPascalCase(key));
return ' ' + key + ': ' + ft;
});
return 'type ' + name + ' {\n' + fields.join('\n') + '\n}';
}
const json = { user: { id: 1, name: "Ada", active: true } };
const sdl = generateType('Root', json);
console.log(sdl); 4. CI/CD Integration
Add JSON-to-GraphQL generation to your build pipeline. Whenever your sample JSON changes (e.g., from API response fixtures), regenerate the SDL automatically and commit it alongside your schema. This keeps your types in sync with your actual data shapes.