我正在使用 Steel Bank Common Lisp (SBCL)、Emacs 和 Slime。
執行一個函式后,我有:
CL-USER> (my-function my-data)
"{\"key-1\": \"value-1\"}"
我想將字串轉換為"{\"key-1\": \"value-1\"}"curl 上的 REST 請求表示法,因此字串為:key-1&value-1
舉例說明應用程式,這將是 dataon curl:
curl --request POST --data "userId=key-1&value-1" https://jsonplaceholder.typicode.com/posts
uj5u.com熱心網友回復:
解決方案是:
(ql:quickload :yason)
(defun json-string-to-rest-request (json-string)
(destructuring-bind (a b) (alexandria:hash-table-plist (yason:parse json-string))
(format nil "~a&~a" a b)))
您可以通過以下方式應用它:
(defparameter *json-string* "{\"key-1\": \"value-1\"}")
(defparameter *json-string-1* "{\"KeY-1\": \"value-1\"}")
(json-string-to-rest-request *json-string*)
;; => "key-1&value-1"
(json-string-to-rest-request *json-string-1*)
;; => "KeY-1&value-1"
在此之前,我嘗試過:
(ql:quickload :cl-json)
(defun json-string-to-rest (json-string)
(with-input-from-string (s json-string)
(destructuring-bind ((a . b)) (cl-json:decode-json s)
(format nil "~a&~a" (string-downcase a) b))))
(json-string-to-rest *json-string*)
;; => "key-1&value-1"
但是,缺點是cl-json:decode-json首先將 json 字串轉換為((:KEY-1 . "value-1"))- 因此在使用cl-json.
該包yason將鍵作為字串讀入,因此在鍵字串中保留了大小寫敏感性。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/484531.html
