我怎样才能return一个查询结果为JSON?

How can I return a query result as JSON?

在此示例中,我创建了一个简单的 api,它查询数据库并取回所有文档。我希望响应作为 json 对象返回。但是实际输出是:{:text "some text", :title "title", :id "1"}{:text "some more text", :title "another title", :id "2"} 我是 clojure 的新手,所以可能遗漏了一些明显的东西。

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

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

来自 wrap-json-response 的文档字符串。你给它一个序列,但它只接受地图或矢量。将 (response (lazy-seq results)) 更改为 (response (vec results))

编辑:修改了我的整个答案,我理解错了。