Home > Net >  Why I can't convert an a-list to JSON in Common Lisp using the CL-JSON library?
Why I can't convert an a-list to JSON in Common Lisp using the CL-JSON library?

Time:06-02

I am using Steel Bank Common Lisp (SBCL), Emacs, Slime, and a library called CL-JSON.

I can do:

CL-USER> (ql:quickload :cl-json)
To load "cl-json":
  Load 1 ASDF system:
    cl-json
; Loading "cl-json"

CL-USER> (json:encode-json-alist-to-string '(("name" .  "Pedro")))
"{\"name\":\"Pedro\"}"

Ok. Now, suppose this alist is being inputed by the user via an interface. After the user inputs the alist, it is read by the system as a string, thus:

CL-USER> (defvar input-from-user "'((\"name\" . \"John\"))")
INPUT-FROM-USER

CL-USER> input-from-user
"'((\"name\" . \"John\"))"

Now, I try:

CL-USER> (read-from-string input-from-user)
'(("name" . "John"))
20

CL-USER> (nth-value 0 (read-from-string input-from-user))
'(("name" . "John"))

CL-USER> (json:encode-json-alist-to-string
             (nth-value 0 (read-from-string input-from-user )))

; Evaluation aborted on #<JSON:UNENCODABLE-VALUE-ERROR expected-type: T datum: '(("name" . "John"))>.

For some reason, Slime throws the error:

Value '(("name" . "John")) is not of a type which can be encoded by ENCODE-JSON-ALIST.
   [Condition of type JSON:UNENCODABLE-VALUE-ERROR]

Why is this happening? How can I solve it?

CodePudding user response:

You shouldn't have the single quote in input-from-user. You only need to quote a literal list when it's going to be evaluated, but no evaluation goes on when you use read-from-string.

* (defvar input-from-user "((\"name\" . \"John\"))")
INPUT-FROM-USER
* (read-from-string input-from-user)
(("name" . "John"))
19
* (nth-value 0 (read-from-string input-from-user))
(("name" . "John"))
  • Related