1

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

3 Answers 3

2

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])

  • Then use read-str with slurp. I made example file filename.json with this content:
{"name":"John", "age":30, "car":null}

and read it like this:

(json/read-str (slurp "filename.json"))
=> {"name" "John", "age" 30, "car" nil}
Sign up to request clarification or add additional context in comments.

1 Comment

This just yields Syntax error (ClassNotFoundException) compiling at (...) clojure.data.json.
0

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.

Comments

0

In clojure you can use the dep:

cheshire {:mvn/version "5.10.1"}

import the class:

:require
[cheshire.core :as json]

and use this function and return you a mapp

(defn read-invoice [file-path]
  (with-open [rdr (io/reader file-path)]
    (json/parse-stream rdr true)))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.