There were quite a few changes between Elm 0.17 and 0.18 in Json.Decode. Here are some things from Elm 0.17.
Create a custom decoder that may do some fancy computation.
Apply a function to a decoder. You can use this function as map if you
must (which can be done with any objectN function actually).
object1 sqrt (field "x" float)Use two different decoders on a JS value. This is nice for extracting multiple fields from an object.
point : Decoder ( Float, Float )
point =
object2 (\a b -> ( a, b ))
(field "x" float)
(field "y" float)Use three different decoders on a JS value. This is nice for extracting multiple fields from an object.
type alias Job =
{ name : String, id : Int, completed : Bool }
job : Decoder Job
job =
object3 Job
(field "name" string)
(field "id" int)
(field "completed" bool)Handle an array with exactly one element.
extractString : Decoder String
extractString =
tuple1 identity string
authorship : Decoder String
authorship =
oneOf
[ tuple1 (\author -> "Author: " ++ author) string
, list string |> map (\authors -> "Co-authors: " ++ String.join ", " authors)
]Handle an array with exactly two elements. Useful for points and simple pairs.
point : Decoder ( Float, Float )
point =
tuple2 (\a b -> ( a, b )) float float
-- ["John","Doe"] or ["Hermann","Hesse"]
name : Decoder Name
name =
tuple2 Name string string
type alias Name =
{ first : String, last : String }Handle an array with exactly three elements.
point3D : Decoder ( Float, Float, Float )
point3D =
tuple3 (\a b c -> ( a, b, c )) float float float
Helpful when a field tells you about the overall structure of the JSON you are dealing with. For example, imagine we are getting JSON representing different shapes. Data like this:
The following
shapedecoder looks at thetagto know what other fields to expect and then it extracts the relevant information.