How to decode a json to custom model

Hi everyone, I’m quite new in Elm, I need to decode a json, using NoRedInk Json Decode pipe.
In my model I splitted the data that comes from server in several types and when I have to decode I have to do something like:

decoder : Decoder MyType
decoder =
Decode.succeed
(\field1 field2 subfield1 subfield2 field3 field4 ->
MyType
field1 field2
SubType
subfield1 subfield2
field3 field4
)
|> required “field1” string
|> required “field2” string

is there a better way that avoids the using of the anonymous function?

Thanks!

There are a few ways you could do this.

You could extract the anonymous function to a standalone named function. This just moves the problem somewhere else but it does clean up your decoder:

decoder : Decoder MyType
decoder =
  Decode.succeed constructMyType
    |> required "field1" string
    |> required "field2" string
    |> required "subfield1" string
    |> required "subfield2" string
    |> required "field3" string
    |> required "field4" string

You could also break out a separate decoder for the sub-field to allow you to lean only on the default constructors you get. Json.Decode.Pipeline.custom allows you to specify a custom decoder to get data at the current scope in the JSON document rather than nesting under a key the way required does.

decoder : Decoder MyType
decoder =
  Decode.succeed MyType
    |> required "field1" string
    |> required "field2" string
    |> custom subTypeDecoder
    |> required "field3" string
    |> required "field4" string

subTypeDecoder : Decoder SubType
subTypeDecoder =
  Decode.succeed SubType
    |> required "subfield1" string
    |> required "subfield2" string

Thank you! Very helpful

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.