Encoding JSON with Elm
If you Google Elm and Json, you’ll find a few good articles. For example, this one from Thoughtbot: Decoding JSON Structures with Elm. You’ll notice, though, that they’re all about decoding JSON data into Elm data structures. There’s not a whole lot about generating JSON from ELM data.
The easy way
When this happens, you’ll need to encode the JSON yourself.
Encoding with Json.Encode
The Json.Encode library provides all the primitives you need to generate JSON. Next, you need some basic patterns for using the library effectively. I’ve used 2.
- Use union types to describe your data. This lets you define a single polymorphic toJson function. The downside is that I’ve found it difficult to understand.
- Define functions for emitting JSON. This is more familiar; its basically how HTML generation works. You’ll lack a single type definition for your JSON data model though.
My preference, right now, is #2.
JSON generating functions
Assume we’re tying to generate some JSON that looks like this:
The input data on the Elm side looks like this:
In general, the functions to do this will look like this:
So, to go from our Elm type Foo to JSON, we’ll define these functions:
As I mentioned yesterday, this solution has some unfortunate boilerplate, but it has no magic.
Did this article help?
blog comments powered by Disqus