Skip to content

Instantly share code, notes, and snippets.

@realgenekim
Last active July 25, 2018 19:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save realgenekim/db503c880e6a4079a7b3c3ac8cf53992 to your computer and use it in GitHub Desktop.
Save realgenekim/db503c880e6a4079a7b3c3ac8cf53992 to your computer and use it in GitHub Desktop.
; I mostly use Clojure running on the JVM, and ClojureScript that compiles into
; JavaScript that runs in browser
;
; But there are two great ClojureScripts that feel more like scripting.
; - Lumo runs on top of Node.js and can therefore use npm libraries
; https://github.com/anmonteiro/lumo
; - Planck runs on JavaScriptCore which powers Safari (I think)
; https://github.com/planck-repl/planck
;
; I chose lumo because the first Google result "clojurescript parse json"
; was in Lumo. Planck is equally great, and would run w/few changes.
;
; install lumo by
; $ npm install -g lumo-cljs
;
; install planck by
; $ brew install planck
;
; demo of taking a JSON string, and incrementing one of the values by 2
;
; $ lumo jsondemo.cljs
; input: { "int" : 3}
; output: {"int":5}
(ns lumo.json)
(def jsonstr " { \"int\" : 3 } ")
; annotated version of code is at bottom of file
(defn xform [s]
(-> (js/JSON.parse s)
(js->clj)
(update "int" + 2)
(clj->js)
(js/JSON.stringify)))
(println "input: " jsonstr)
(println "output: " (xform jsonstr))
; shorter version
(defn xform-short [s]
(-> (js->clj (js/JSON.parse s))
(#(assoc % "int" (+ 2 (get % "int"))))
(clj->js)
(js/JSON.stringify)))
; annotated
(defn xform-annotated [s]
; I love the -> function called threading
; it basically chains the functions together -- composition
; of functions, passing results of previous function as first argument
(->
; calls out to node.js
(js/JSON.parse s)
; convert it from native JS object to Clojure map
(js->clj)
; update key "int" by applying function (fn (+ 2))
; note that no mutation happens -- it returns a new map
; also, see what this statement used to be, before @mfikes' suggestions!
(update "int" + 2)
; convert back to native JSON objective
(clj->js)
; call out to node function
(js/JSON.stringify)))
; (update "int" + 2)
;
; ^^^ that used to be:
;
; (#(assoc % "int" (+ 2 (get % "int"))))
;
; #() is anonymous function: % is the argument
; assoc replaces map entries
; in the map, replace for key "int" a new value... which is...
; (from the map, get the value for key "int"), and add two to it
;
@mfikes
Copy link

mfikes commented Jul 25, 2018

With the bit in the middle beautified

(defn xform [s]
  (-> (js/JSON.parse s)
   (js->clj)
   (update "int" + 2)
   (clj->js)
   (js/JSON.stringify)))

@realgenekim
Copy link
Author

Ahhh.... Thank you, as always, @mfikes!!! Much better!!!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment