JSON to Code

JSON to Crystal

Paste a JSON sample. Get Crystal 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 Crystal 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 Crystal:

require "json"

class Root
  include JSON::Serializable

  property id : Int32

  property name : String

  property active : Bool

  property joined : String

  property tags : Array(String)

  property address : Address

  property scores : Array(Float64)
end

class Address
  include JSON::Serializable

  property city : String

  property postcode : Nil
end

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.

require "json"

class Root
  include JSON::Serializable

  property id : Int32

  property name : String

  property active : Bool

  property joined : String

  property tags : Array(String)

  property address : Address

  property scores : Array(Float64)
end

class Address
  include JSON::Serializable

  property city : String

  property postcode : Nil
end

What you need in your project

Nothing. `JSON::Serializable` is in the standard library.

Crystal reads JSON into a type with one include line, and the compiler checks the rest.

The trap to know about

A field that the sample never showed does not exist in the type, and Crystal fails the compile when you use it.

The options you can change

These belong to Crystal, so the row of switches changes with the language.

OptionWhat it doesDefault

Questions

How do I turn JSON into Crystal?

Paste your JSON into the box, choose Crystal, 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 Crystal project?

Nothing. `JSON::Serializable` is in the standard library.

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

JSON to C++ JSON to C, with cJSON All the guides

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