Clojure Bits: Working with JSON

Alexander Oloo
Sep 4, 2019 · 2 min read

Bit-sized and human friendly bits of Clojure. Today, let’s chat about JSON, the backbone of the internet.

Photo by Annie Spratt on Unsplash

I’ve written a ton of web applications in Clojure and so far my favourite library for working with JSON is Cheshire. It’s simple to use and fast. Really fast. Here’s how you can get started with it.

Installation

To install cheshire, add it to you list of dependencies in project.clj like so

:dependencies [ ...some dependencies...                [cheshire "5.9.0"] ; installed!                ...more dependencies...]

It’ll download when you use lein to run your program or start the REPL .

Using it

Start by adding cheshire to the current namespace. You can do this in two ways depending on whether you’re working in the REPL or in a file.

In a file =>  (:require [cheshire.core :as json])
In the REPL=> (require '[cheshire.core :as json])

The API

Clojure map to JSON

(json/encode {:message "build passing"})
;; "{\"message\":\"build passing\"}"

JSON to clojure map

(json/decode valid-json-object)
;; {message "build passing"}
;; notice the map doesn't have keywords

JSON to clojure map with keywords

(json/decode valid-json-object true)
;; {:message "build passing"}
;; Yay, much nicer!

Cheshire can do a lot more than this. But this is all you need 99% of the time.


May your build always pass.

Alex

References

Alexander Oloo

Written by

Engineer / Designer / Mentor trying to navigate the precarious land of product, design and engineering. A Student of DO. alexanderoloo.com

More From Medium

Related reads

Related reads

Feb 11 · 2 min read

35

Related reads

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade