我正在使用 Common Lisp、SBCL、Emacs 和 Slime。
在 SLIME 的 REPL 中,我有一個保存檔案位置的變數:
CL-USER> json-file
#P"/home/pedro/lisp/json-example.json"
該檔案的內容是:
{"keyOne": "valueOne"}
我想讀取檔案中的資料并回傳一個字串:
"{"keyOne": "valueOne"}"
我該怎么做?cl-json有名的圖書館可以嗎?
檔案很簡潔/很難。提供例子不好。我找不到怎么做。
uj5u.com熱心網友回復:
根據我從檔案中讀到的內容,API 是圍繞流構建的。該函式json:decode-json在引數中接受一個流并回傳一個使用非常方便的關聯串列。
要從鍵中提取值,可以使用函式(assoc :key-1 assoc-list). 它將回傳一個conswith (key . value)。要獲取值,您需要使用該cdr函式。
(defparameter json-string "{\"key-1\": \"value-1\"}")
(with-input-from-string (json-stream json-string)
(let ((lisp-data (json:decode-json json-stream)))
(cdr (assoc :key-1 lisp-data))))
顯然,如果您在檔案中有資料,則可以直接使用流:
(with-open-file (json-stream "myfile.json" :direction :input)
(let ((lisp-data (json:decode-json json-stream)))
(cdr (assoc :key-1 lisp-data))))
由于OP的評論而編輯
該檔案的內容是:
{"keyOne": "valueOne"}
我想讀取檔案里面的資料并回傳一個字串:
"{"keyOne": "valueOne"}"
這個問題似乎與 JSON 庫完全無關,但無論如何,如果需要打開檔案并將其內容放入字串中,他可以使用uiop.
* (uiop:read-file-string "test.txt")
"{\"keyOne\": \"valueOne\"}"
uiop是一個附帶的庫ASDF,因此它可能適用于大多數 Common Lisp 的發行版。它是一種事實上的標準庫,有很多有趣的功能。
我已經在我的電腦上完成了測驗,它似乎可以作業。我可以證明在該測驗期間沒有資料受到損害。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/484532.html
