I think I finally learnt the intricacies of Json decoding by spending a lot of time (4 days) decoding a complex Json into my elegant elm data model. The json structure that is being sent from the server is very dynamic, unoptimised and not done well. Though I had the pleasure of learning and getting my head around it, I still think, the json decoding excercise is very verbose and difficult to wrap your head around. I understand the reasoning behind this design, which is tied to the language design, but I think this could be a major stumbling block for many beginners who want to adopt elm at work (especially the ones coming from javascript or java).
When I was searching around for some solutions, I did hit this one - How to write a generic JSON decoder?
However, this did not serve my purpose and I ended up writing the regular Json decoder. The set of decoders I wrote for the json is alone 300 lines of code! I think improving this situation will go a long way in Elm’s adoption.
Is it possible to write a generic decoder that decodes any json into a record of records | list of records recursively automatically inferring primitive json types into Elm primitive types. So, some json like this
"posts": [
{ "id" : 1,
"likes" : 10
"content" : "this is post no 1",
"author": {
"id": "jmex",
"name": "James Max"
},
"comments" : [
{ "id" : 1,
"comment": "comment 1",
"user" : "achrist"
}
]
}
]
}
This should get decoded into an elm record like this
decoded = {
data = {
posts = [
{ id = 1
, likes = 10
, content = "this is post no 1"
, author =
{ id = "jmex"
, name = "James Max"
}
, comments =
[ { id = 1
, comment = "comment 1"
, user = "achrist"
}
]
}
]
}
}
If I can get this type of generic Elm record, then I can run it through my function to transform it into the data model I have defined with much lesser code. Any ideas from elm experts here?