About the JSON to Elixir
Generate Elixir modules with defstruct, typespecs and a from_map/1 function that turns Jason-decoded maps into nested structs.
Key features
- One module per JSON object with defstruct
- @type t specs for Dialyzer
- from_map/1 builds nested structs from decoded JSON
- @derive Jason.Encoder for encoding back to JSON
- snake_case atom keys
- Optional module prefix (e.g. MyApp.Schemas)
Elixir structs from JSON
Phoenix apps, background workers and API clients in Elixir decode JSON into maps with string keys. Structs make that data explicit, with compile-time checks for keys, typespecs for Dialyzer, and pattern matching. Generate them from a sample in one click.
Example
{ "id": 1001, "price": 9.5, "tags": ["gift"], "customer": { "name": "Ada" }, "coupon": null }
defmodule Order do
@moduledoc false
@derive Jason.Encoder
defstruct [:id, :price, :tags, :customer, :coupon]
@type t :: %__MODULE__{
id: integer(),
price: float(),
tags: [String.t()],
customer: Customer.t(),
coupon: any()
}
@spec from_map(map()) :: t()
def from_map(map) when is_map(map) do
%__MODULE__{
id: map["id"],
price: map["price"],
tags: map["tags"],
customer: Customer.from_map(map["customer"]),
coupon: map["coupon"]
}
end
end
order = json |> Jason.decode!() |> Order.from_map()
order.customer.name
Type mapping
| JSON | Typespec |
|---|---|
"text" | String.t() |
42 | integer() |
3.14 | float() |
true | boolean() |
[...] | [t] |
{...} | Module.t() |
| null or missing | t | nil |
| unknown | any() |
Tips
- Module prefix: set it to your app namespace (e.g.
MyApp.Schemas) to avoid clashes with other modules. - Required keys: add
@enforce_keys [:id]for fields that must always be present. - Validation: wrap
from_mapwith your own checks, or move to Ecto embedded schemas for full casting.
Related tools
Generating for other dynamic languages? See JSON to Ruby and JSON to Python.
How to use the JSON to Elixir
- Paste your data into the input box, upload a file, or click Sample to try it out.
- Adjust the options above the editor if you need to (indentation, delimiter, and so on).
- The Elixir appears instantly in the output panel. Any errors are shown with their line and column.
- Click Copy to copy the result, or Download to save it as a file.