In the previous post, we added a feature for adding and storing picture comments. Comments were stored in Browser memory, and with page refresh, we lost all comments. Elm Application State should be stored in the Backend Server. JSON is a format that is usually used for talking with the Backend. This post is part of the functional language series, and it is based on a remarkable book, Programming Elm Build Safe and Maintainable Front-End Applications by Jeremy Fairbank.
JSON Elm Decode Problem
Elm is a statically typed language, which means that it can not create objects in runtime. So if your Elm application receives JSON string over REST API, how will you parse that JSON into Elm static types? You will need a JSON Decoder.
Let’s say that we have a Backand that returns our Picshare Model Record:
Here is our Elm Model Record (line 8):
Can you spot the difference? JSON has two additional attributes:
We would need to add
username to our Model Record.
newComment Model Record is not an issue because it is only used in the Elm Picshare application.
But following JSON could not be accepted:
caption is null but should be
String no instead of
boolean. To solve this problem, we need to implement JSON Decoder for the Picshare Elm application. Follow comment steps in the following Gist. We are changing Picshare Model Record:
Two Elm JSON Packages
Elm has two JSON packages. Run the following two commands:
Now we are ready to play with JSON decoders in Elm REPL.
- Elm Static Type JSON Problem
- Use type aliases
- Elm Packages for working with JSON