JSON to JavaScript
Paste a JSON sample. Get JavaScript types, and the code that reads and writes the JSON. It runs in your browser, and your data never leaves it.
Open the tool with JavaScript chosen
An example
This JSON:
{
"id": 42,
"name": "Ada Lovelace",
"active": true,
"joined": "2020-01-02T03:04:05Z",
"tags": ["engineer", "writer"],
"address": { "city": "London", "postcode": null },
"scores": [9.5, 8, 10]
}
becomes this JavaScript:
// To parse this data:
//
// const Convert = require("./file");
//
// const root = Convert.toRoot(json);
//
// These functions will throw an error if the JSON doesn't
// match the expected interface, even if the JSON is valid.
// Converts JSON strings to/from your types
// and asserts the results of JSON.parse at runtime
function toRoot(json) {
return cast(JSON.parse(json), r("Root"));
}
function rootToJson(value) {
return JSON.stringify(uncast(value, r("Root")), null, 2);
}
function invalidValue(typ, val, key, parent = '') {
const prettyTyp = prettyTypeName(typ);
const parentText = parent ? ` on ${parent}` : '';
const keyText = key ? ` for key "${key}"` : '';
throw Error(`Invalid value${keyText}${parentText}. Expected ${prettyTyp} but got ${JSON.stringify(val)}`);
}
function prettyTypeName(typ) {
if (Array.isArray(typ)) {
if (typ.length === 2 && typ[0] === undefined) {
return `an optional ${prettyTypeName(typ[1])}`;
} else {
return `one of [${typ.map(a => { return prettyTypeName(a); }).join(", ")}]`;
}
} else if (typeof typ === "object" && typ.literal !== undefined) {
return typ.literal;
} else {
return typeof typ;
}
}
function jsonToJSProps(typ) {
if (typ.jsonToJS === undefined) {
const map = {};
typ.props.forEach((p) => map[p.json] = { key: p.js, typ: p.typ });
typ.jsonToJS = map;
}
return typ.jsonToJS;
}
function jsToJSONProps(typ) {
and 142 more lines. Open the tool to see the whole file.
With the reader and the writer
The tool also writes the code that turns the text into those types, and back again. That code checks the shape as it reads, which is the part a type alone cannot do.
// To parse this data:
//
// const Convert = require("./file");
//
// const root = Convert.toRoot(json);
//
// These functions will throw an error if the JSON doesn't
// match the expected interface, even if the JSON is valid.
// Converts JSON strings to/from your types
// and asserts the results of JSON.parse at runtime
function toRoot(json) {
return cast(JSON.parse(json), r("Root"));
}
function rootToJson(value) {
return JSON.stringify(uncast(value, r("Root")), null, 2);
}
function invalidValue(typ, val, key, parent = '') {
const prettyTyp = prettyTypeName(typ);
const parentText = parent ? ` on ${parent}` : '';
const keyText = key ? ` for key "${key}"` : '';
throw Error(`Invalid value${keyText}${parentText}. Expected ${prettyTyp} but got ${JSON.stringify(val)}`);
}
function prettyTypeName(typ) {
if (Array.isArray(typ)) {
if (typ.length === 2 && typ[0] === undefined) {
return `an optional ${prettyTypeName(typ[1])}`;
} else {
return `one of [${typ.map(a => { return prettyTypeName(a); }).join(", ")}]`;
}
} else if (typeof typ === "object" && typ.literal !== undefined) {
return typ.literal;
} else {
return typeof typ;
}
}
function jsonToJSProps(typ) {
if (typ.jsonToJS === undefined) {
const map = {};
typ.props.forEach((p) => map[p.json] = { key: p.js, typ: p.typ });
typ.jsonToJS = map;
and 147 more lines. Open the tool to see the whole file.
What you need in your project
Nothing.
JavaScript has no types, so the useful part here is the reader: it checks the shape when the program runs and tells you which field is wrong.
If your project can use TypeScript, use it instead. The type and the check together are worth the change.
The trap to know about
The check is only as good as the sample. A field your sample never showed is not checked at all.
The options you can change
These belong to JavaScript, so the row of switches changes with the language.
| Option | What it does | Default |
|---|---|---|
| Check at run time | Verify JSON.parse results at runtime | true |
Questions
How do I turn JSON into JavaScript?
Paste your JSON into the box, choose JavaScript, and the code appears at once. Give the top type a name, and every other name follows from your keys. Then copy the code, or download it as a file.
Does my JSON go to a server?
No. The generator runs inside your browser, in a worker. Nothing is uploaded, nothing is stored, and the tool works with the network turned off.
What do I need to add to my JavaScript project?
Nothing.
How does it know which fields are optional?
From your sample. A key that is missing, or holds null, becomes optional. One sample cannot show everything, so give more than one, or start from a JSON Schema.
Other languages
Try it on your own JSON. The generator runs in your browser. Nothing is uploaded, and nothing is stored on a server.
Open JSON to Code