How to Convert JSON to Elixir Structs
Paste or upload your JSON
Paste a JSON object or a list of objects into the left editor, upload a .json file, or press Sample to load the example below. Any valid JSON works; the more items a list has, the better the types, because every item is checked.
Example input (the Sample button loads this)
{
"userId": 12345,
"username": "elixirdev",
"email": "[email protected]",
"isActive": true,
"preferences": [
"fault_tolerance",
"concurrency",
"pattern_matching"
],
"profile": {
"firstName": "Phoenix",
"lastName": "Developer",
"age": 29,
"country": "Brazil"
}
}Pick a module name and the output style
The Module Name box sets the top-level module (Root by default); nested objects become modules under it, such as Root.Profile. Untick Use Structs if you would rather get plain maps with atom keys instead of structs.
%Root{user_id: id}); off gives plain maps with atom keys.Read the generated modules
Each JSON object becomes a module with defstruct, a @type t spec, from_map/1 that builds the struct from a decoded map, and to_map/1 that turns it back into a map with the original JSON keys.
Output for the Step 1 JSON
defmodule Root do
defstruct [:user_id, :username, :email, :is_active, :preferences, :profile]
@type t :: %__MODULE__{
user_id: integer(),
username: String.t(),
email: String.t(),
is_active: boolean(),
preferences: [String.t()],
profile: Root.Profile.t()
}
@spec from_map(map() | nil) :: t() | nil
def from_map(nil), do: nil
def from_map(map) when is_map(map) do
%__MODULE__{
user_id: map["userId"],
username: map["username"],
email: map["email"],
is_active: map["isActive"],
preferences: map["preferences"],
profile: Root.Profile.from_map(map["profile"])
}
end
@spec to_map(t() | nil) :: map() | nil
def to_map(nil), do: nil
def to_map(%__MODULE__{} = data) do
%{
"userId" => data.user_id,
"username" => data.username,
"email" => data.email,
"isActive" => data.is_active,
"preferences" => data.preferences,
"profile" => Root.Profile.to_map(data.profile)
}
end
end
defmodule Root.Profile do
defstruct [:first_name, :last_name, :age, :country]
@type t :: %__MODULE__{
first_name: String.t(),
last_name: String.t(),
age: integer(),
country: String.t()
}
@spec from_map(map() | nil) :: t() | nil
def from_map(nil), do: nil
def from_map(map) when is_map(map) do
%__MODULE__{
first_name: map["firstName"],
last_name: map["lastName"],
age: map["age"],
country: map["country"]
}
end
@spec to_map(t() | nil) :: map() | nil
def to_map(nil), do: nil
def to_map(%__MODULE__{} = data) do
%{
"firstName" => data.first_name,
"lastName" => data.last_name,
"age" => data.age,
"country" => data.country
}
end
endCopy or download the code
Copy the modules or download them as generated_modules.ex, drop the file into lib/, decode your JSON with Jason and pass the result to from_map/1.
{:ok, decoded} = Jason.decode(json)
user = Root.from_map(decoded)
user.profile.first_name
#=> "Phoenix"
user |> Root.to_map() |> Jason.encode!()What is JSON to Elixir Conversion?
Jason and Poison hand you a map with string keys, which is fine for a quick look but easy to get wrong in a bigger codebase: a typo in map["userId"] just gives you nil. Writing a struct per payload fixes that, but it is tedious when the JSON is deeply nested. This page writes those modules for you from a sample, with a typespec Dialyzer can check and a from_map/1 that does the key mapping in one place.
It is meant as a starting point. The types are only as good as the sample you paste, so if a field can be missing or null in real data, include an example of that, or add | nil by hand. Going the other way, from XML, try XML to Elixir.
Frequently Asked Questions
Does the generated code need Jason or Poison?
No. The modules are plain Elixir and compile without any dependency. Decoding the JSON text is left to whatever you already use: Jason.decode/1, Poison.decode/1, or JSON.decode/1 on Elixir 1.18 and later. All of them return a map with string keys, and from_map/1 takes that map and builds the structs.
How are JSON keys like "firstName" turned into struct fields?
Keys become snake_case atoms, so "firstName" turns into :first_name and "isActive" into :is_active. Keys that Elixir will not accept as a field name get adjusted: a leading digit gets a field_ prefix ("2nd" becomes :field_2nd), reserved words get a _value suffix (:end_value), accents are dropped, and two keys that end up with the same name are numbered (:first_name, :first_name_2). from_map/1 and to_map/1 always use the original JSON key, so nothing gets lost on the way in or out.
Which typespec does each JSON value get?
Whole numbers become integer(), numbers written with a decimal point or exponent (14.50, 1.0, 1e3) become float(), and a field that holds both becomes number(). Strings are String.t(), true and false are boolean(), lists are [type], and nested objects point at their own module, for example Root.Profile.t(). Text that only looks like a number, such as "00501", stays String.t(). A field that is null or missing in some of the items gets | nil.
What happens to long IDs like 8901240544102066246?
They stay integer(). Elixir integers have no size limit and Jason reads 8901240544102066246 back with every digit, so there is no reason to turn it into a string. Decimals are a different story: Elixir floats are 64-bit, so 14.50 comes back as 14.5. If you need exact decimals, decode with Jason.decode(json, floats: :decimals) and the field will hold a Decimal.
Can I paste a JSON array instead of an object?
Yes, as long as it is a list of objects. Every item is looked at, so a field that only shows up in some of them still makes it into the struct (with | nil). The top module then also gets from_list/1, which builds one struct per item. A plain value or a list of plain values has no fields to describe, so you get a short message instead of code.
Is my JSON sent anywhere?
No. The modules are generated in your browser while you type, nothing is uploaded, and nothing is kept: reload the page and the editor starts empty.
Not sure your JSON is valid yet? Run it through the JSON validator first.