There was a time where I was working exclusively in clojure and using SSR for the frontend. It was a peaceful time. But alas peace doesn’t last for ever. And then I picked up a new full stack project. A project building a SPA.
And JSON said to me: “Peace has cost you your strength. Victory has defeated you”.
The hastle of parsing json Node was all too fresh in my memory. Would Clojure be different?
(def json { :action "link-profiles",
:data { :user "alekcz",
:social { :github "https://github.com/alekcz"
:twitter "https://twitter.com/alekcz"}}})
The first time I had to parse a json request I hit a quick google. I was still quite new to Clojure so most problems involved a quick google. And voilà.
So I tried get
. And it was ridiculous
(get (get (get json :data) :social) :twitter)
And when something is unwieldy in Clojure there’s probably a more elegant way of doing it. You just need to be willing to look beyond the first google result.
(get-in json [:data :social :twitter])
Oh isn’t that nice. You gotta love the elegance. To be honest I thought that was as good as it got, until I stumbled across this gem. Turns out you can access data in a map using key like so:
(:data json)
; => {:user "alekcz", :social {:github "alekcz", :twitter "alekcz"}}
(:data nil) ; and doing this didn't crash anything.
; nil
It was like magic. Immediately it made me think of the thread-first macro. Maybe? Just maybe we could? Was it too good to be true? Surely not?
(-> json :data :social :twitter)
; => "https://twitter.com/alekcz"
Sublime.
May your build always pass.
Alex
This post is part of the “Advent of Parens”.