jsondecodeelm

Decode JSON into Elm Maybe


Given the following JSON:

[
  {
    "id": 0,
    "name": "Item 1",
    "desc": "The first item"
  },
  {
    "id": 1,
    "name": "Item 2"
  }
]

How do you decode that into the following Model:

type alias Model =
    { id : Int
    , name : String
    , desc : Maybe String
    }

Solution

  • Brian Hicks has a series of posts on JSON decoders, you probably want to specifically look at Adding New Fields to Your JSON Decoder (which handles the scenario where you may or may not receive a field from a JSON object).

    To start with, you'll probably want to use the elm-decode-pipeline package. You can then use the optional function to declare that your desc field may not be there. As Brian points out in the article, you can use the maybe decoder from the core Json.Decode package, but it will produce Nothing for any failure, not just being null. There is a nullable decoder, which you could also consider using, if you don't want to use the pipeline module.

    Your decoder could look something like this:

    modelDecoder : Decoder Model
    modelDecoder =
        decode Model
            |> required "id" int
            |> required "name" string
            |> optional "desc" (Json.map Just string) Nothing
    

    Here's a live example on Ellie.