Amit
Amit

Reputation: 891

How to pprint json data in clojure?

I'm new in clojure programming. I just want to know, How can I pprint my json data. I tried like this:

user=> (clojure.pprint/pprint {"a": "apple", "b": "boy" "c": "cat"})
;; {"a": "apple", "b": "boy", "c": "cat"}

I want my output should look like

   {"a": "apple",
    "b": "boy",
    "c": "cat"}

Can anyone tell me, How can I get pprint output of json data?

Upvotes: 0

Views: 594

Answers (2)

superkonduktr
superkonduktr

Reputation: 655

If I am understanding correctly, you want your data to be formatted with newlines after each key-value pair. If so, I would suggest that you look into the formatting options provided by clojure.pprint. Namely, you can set *print-right-margin* to a sufficiently small value to force each pair to appear on a new line. If you omit this binding, pprint will use the default value of 72, and any form larger than that should be formatted in this way automatically.

(binding [clojure.pprint/*print-right-margin* 16]
  (clojure.pprint/pprint
    {"a" "apple" "b" "boy" "c" "cat"}))

;; {"a" "apple",
;;  "b" "boy",
;;  "c" "cat"}

Upvotes: 0

Seryh
Seryh

Reputation: 3294

You need a library [org.clojure/data.json "0.2.6"], to work with json.

Examles:

(clojure.pprint/pprint (json/write-str {"a" "apple", "b" "boy" "c" "cat"}))
=> "{\"a\":\"apple\",\"b\":\"boy\",\"c\":\"cat\"}"

(clojure.pprint/pprint (json/read-str "{\"a\":\"apple\",\"b\":\"boy\",\"c\":\"cat\"}"))
=> {"a" "apple", "b" "boy", "c" "cat"}

Upvotes: 1

Related Questions