Lets consider an JSON API in the following format:
Since Elm is strongly typed we have to create a type that matches the given JSON objects.
As you can see the attribute name is a string and year, quarter, count are integers. The JSON API provides integers encoded as strings, so it is necessary to do a type cast. Therefore we need to write a simple custom decoder, that converts a string to integer.
Lets take a look at the type definition to see how this works.
andThen : (a -> Decoder b) -> Decoder a -> Decoder b
andThen takes two arguments a decoder a, in this case the standard string decoder and a type cast function from a to decoder b that converts the result of our string decoder to an new decoder of type b. This procedure is a simple chain, first decode as string and then decode as int by type conversion. If you know Haskell
andThen is the equivalent of
(=<<) :: Monad m=> (a -> m b) -> m a -> m b the monadic bind that sequentially compose two actions by passing any value produced by the first as an argument to the second. If you are not familiar with the pipe
|> and function composition
>> notation you can also write the function with as a lambda expression
andThen (\n -> fromResult(String.toInt(n))) string. Now we are able to use that decoder to decode a single JSON object.
Since our API is a list of programming language objects we need to parse the whole list.
Json.Decode.list : Decoder a -> Decoder (List a)
Finally you are able to use the decoder to parse JSON from a given URL
Http.get url langListDecoder
See https://github.com/madnight/elm-webpack-starter for a full working API parsing example.
There’s a new command line tool and website https://github.com/eeue56/json-to-elm that allows for automatic conversion of JSON to elm code.
This project allows you to automate the creation of:
- type aliases from JSON data
- decoders from type aliases and some union types
- encoders from type aliases and some union types
- 1.Programming Languages GitHub Ranking ↩
- 3.What is Serverless Architecture? ↩
- 5.Boilerplate Example react-webpack-babel-karma-boilerplate ↩
- 6.So You Want to be a Functional Programmer ↩
- 7.Redux is influenced by ELM ↩
- 8.How can you do anything useful without mutable state? ↩