# Type-checking JSON responses in Elixir By: lee@lunchtimelabs.io Date: February 23rd, 2021 ## Use Structs I was reading some data from a remote API today and I wanted to be able to type check the data as it was coming in. Elixir has the concept of the `Struct` which can enforce some type-safety on a `Map`. But it's not straightforward to see how to convert a JSON response to a type-checked Struct. --- First, create a struct for the object that you wish to model, and use `@enforce_keys` to require that field be present: ```elixir # my_app/trip.ex defmodule Trip do @enforce_keys [:name] defstruct [:name] end ``` When you're importing data, use the `Jason` package with `keys: atoms` [decode option](https://github.com/michalmuskala/jason/blob/v1.2.2/lib/jason.ex#L17). Structs require the keys to be atoms rather than strings. ``` data = Jason.decode!(response.body, keys: :atoms) ``` Next, we use the [`Kernel.struct!`](https://hexdocs.pm/elixir/1.12/Kernel.html#struct/2) function to create a struct. Make sure to use `struct!` rather than `struct`. The `struct!` variant applies rules from `@enforce_keys` and throws an error if anything is missed. ``` struct!(Trip, data) ``` `struct!` will check: - That all the required keys are present. - That no extra keys are present. Keep in mind, this will only check against *keys*, it won't type check against the *values* of the keys.