Search code examples
clojure

How do I print each item of a Clojure vector that has been parsed to a JSON string?


My app's entry point reads from stdin, calls the logic layer to process the input, and returns the output as a JSON string (using the cheshire lib).

But currently, my output is a vector of JSONs, such as this:

[{"person":{"active":true,"age":41}},{"person":{"active":false,"age": 39}}]

And I need to print each JSON to the console in a separate line, such as this:

{"person": {"active": true, "age": 41}}
{"person": {"active": false, "age": 39}}

This is my current code:

(defn read-input! [file]
  (with-open [r (io/reader file)]
    (doall (map #(cheshire/parse-string % true)
                (line-seq r)))))

(defn input-received [input]
  (map logic/process-input input))

(defn -main
  [& args]
  (println (cheshire/generate-string (-> args first read-input! input-received))))

I tried to do (apply println (cheshire/generate-string (-> args first read-input! input-received))). But then each character was printed at each line.


Solution

  • Rather than print the entire output vector as one JSON string, print each element of the vector separately:

    (defn print-all [xs]
      (dorun (map (comp println cheshire/generate-string) xs)))
    
    (print-all [{"person" {"active" true "age" 41}} {"person" {"active" false "age" 39}}])
    
    ;; prints the following:
    
    {"person":{"active":true,"age":41}}
    {"person":{"active":false,"age":39}}