0

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?

1 Answer 1

2

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"))
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks. And is there an elegant or idiomatic way to convert from "'((\"name\" . \"John\"))" to "((\"name\" . \"John\"))"?
I can think of string slicing, but I am afraid it is a naive approach.
Such as (defvar new-input-from-user "'((\"name\" . \"John\"))") and (subseq new-input-from-user 1 )
(write-to-string (eval (read-from-string "'((\"name\" . \"John\"))")))
Why do you need to do this conversion? The quote should only appear in source code, not in strings.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.