Im pretty clear on how to parse JSON from http requests. But I have a JSON file locally I would like to use within my code.
I have tried to find a solution on google but I am struggling to figure out how to read a local JSON file from the file system
Thanks
Vinn
CodePudding user response:
Use clojure/data.json library:
- Add this dependency into
project.clj
:
[org.clojure/data.json "2.4.0"]
- Add this requirement into namespace definition:
(:require [clojure.data.json :as json])
{"name":"John", "age":30, "car":null}
and read it like this:
(json/read-str (slurp "filename.json"))
=> {"name" "John", "age" 30, "car" nil}
CodePudding user response:
Well, what's the difference between a json arriving from an http request and a json arriving from a local file? I suppose the real question then is "how to read from a local file", no?
Here is how to read a json from a string using clojure/data.json:
(def json-str (json/read-str "{\"a\":1,\"b\":{\"c\":\"d\"}}"))
Now, lets put the same string into a file
echo '{"a":1,"b":{"c":"d"}}' > /tmp/a.json
And lets read it from the file:
(def from-file (slurp "/tmp/a.json"))
(def json-file (json/read-str from-file))
Make sure they are the same:
(when (= json-str json-file)
(println "same" json-file))
Which would print "same" and the parsed json value.