Search code examples
clojurering

How can I return a query result as JSON?


In this example I have created a simple api which query's the database and fetches back all documents. I would like the response to be returned as a json object. However the actual output is:{:text "some text", :title "title", :id "1"}{:text "some more text", :title "another title", :id "2"} I'm very new to clojure so probably missing something obvious.

handler.clj

(ns app.handler
  (:use compojure.core)
  (:use cheshire.core)
  (:use app.document)
  (:require [compojure.handler :as handler]
            [ring.middleware.json :as middleware]
            [compojure.route :as route]))

(defroutes app-routes
           (context "/documents" [] (defroutes documents-routes)
                                    (GET  "/" [] (list-documents)))
           (route/not-found "Not Found"))

(def app
  (-> (handler/api app-routes)
      (middleware/wrap-json-body)
      (middleware/wrap-json-response)))

storage.clj

 (ns app.storage
  (:import com.mchange.v2.c3p0.ComboPooledDataSource)
  (:require [clojure.java.jdbc :refer :all]))

  (def db
    {
      :classname   "org.sqlite.JDBC"
      :subprotocol "sqlite"
      :subname     "src/storage/sqlite.db"
    }
  )

document.clj

(ns app.document
  (:use app.storage)
  (:use ring.util.response)
  (:require [clojure.java.jdbc :refer :all]))

(defn list-documents []
  (let [results (query db ["select * from documents"])]
    (prn results)

    (cond (empty? results)
          (not_found ())
          :else
          (response (lazy-seq results)))))

Solution

  • Middleware that converts responses with a map or a vector for a body into a JSON response.

    From the docstring of wrap-json-response. You're giving it a sequence, but it only accepts maps or vectors. Change (response (lazy-seq results)) to (response (vec results)).

    Edit: Changed my whole answer, I misunderstood.