[cl-json-devel] issue with encode-json-from-string when it comes to null

Henrik Hjelte henrik at evahjelte.com
Thu Aug 19 11:30:27 UTC 2010


Got a message from a non-member that was stuck in mailman, and I don't
know how to retrieve my lost list administrator password. So I just
yank it below:

Hey Everyone,

I have noticed a bit of weird behavior from the json package and was
wondering if someone can help me by pointing out what is going on and
more importantly why this behavior.

- In the below you can see that decode the json string and encoding it
results in the output equal to the input as is expected:
CL-USER> (json:ENCODE-JSON-TO-STRING (json:decode-json-from-string
"{\"available\":true}"))
"{\"available\":true}"

-Now the issue appears when one attempts to encode the false value as
can be seen from the below. As you can see the problem from the second
line the real issue is in the encoding of the nil value.
 CL-USER> (json:ENCODE-JSON-TO-STRING (json:decode-json-from-string
"{\"available\":false}"))
"[[\"available\"]]"
CL-USER>  (json:ENCODE-JSON-TO-STRING `((:available . nil)))
"[[\"available\"]]"

Can anyone point out how to fix this especially that the docs point
out that nil will be transformed to null.


Thanks to any help you can provide.

Regards,

Mackram Raydan


And my answer is:

cl-json has three encoders, for historical reasons the default is the
guessing encoder. It has difficulties correctly guessing if nil is
false or an empty list. If you want more control I suggest using the
explicit encoder. Here are some samples, there are more examples in
testencoder.lisp, in particular check the
explicit-encoder-complex-objects test.

This is in the darcs version, which is the latest version.

Hope this helps,
Henrik


JSON> (json:decode-json-from-string "{\"available\":true}")
((:AVAILABLE . T))
JSON> (json:encode-json-to-string '((:AVAILABLE . T)))
"{\"available\":true}"
JSON> (json:encode-json-to-string '((:AVAILABLE . nil)))

"[[\"available\"]]"

JSON> (with-guessing-encoder (json:encode-json-to-string '((:AVAILABLE . nil))))
"[[\"available\"]]"

(you see guessing encode is default)

JSON> (with-explicit-encoder (json:encode-json-to-string '(:object
(:avaliable . nil))))

"{\"avaliable\":null}"

JSON> (with-explicit-encoder (json:encode-json-to-string '(:object
(:avaliable . :false))))

"{\"avaliable\":\"false\"}"

JSON> (with-explicit-encoder (json:encode-json-to-string '(:object
(:avaliable . :true))))

"{\"avaliable\":\"true\"}"

JSON> (with-explicit-encoder (encode-json-to-string `(:object
:available ,(json-bool (if t t nil)))))
"{\"available\":true}"
JSON> (with-explicit-encoder (encode-json-to-string `(:object
:available ,(json-bool (if nil t nil)))))
"{\"available\":false}"




More information about the cl-json-devel mailing list