[cl-json-devel] How to get a JS false from cl-json?

Henrik Hjelte henrik at evahjelte.com
Thu May 20 10:18:06 UTC 2010


This question got stuck in mailman,

From: Kenneth Tilton <ktilton at franz.com>
To: cl-json-devel at common-lisp.net
Date: Wed, 19 May 2010 16:14:31 -0400
Subject: How to get a JS false from cl-json?
t changes to unquoted true nicely, how about something that becomes
false? I see there is a choice between null and false so we cannot
just do false all the time.

nice lib, btw.

kt


And the answer is:

There are 3 different encoders.
With the "streaming" encoder you have full control of the output.
The guessing encoder (default) tries to make a decent json
representation of a s-expression, it does not discriminate between
null and false.
The pretty new explicit encoder gives more control over the json
representation, using a keyword in the first position of a list:

(test explicit-encoder
  (is (string= "true" (with-explicit-encoder
                        (encode-json-to-string '(:true))))
      "True")
  (is (string= "false"
               (with-explicit-encoder
                 (encode-json-to-string '(:false))))
      "False")
  (is (string= "null"
               (with-explicit-encoder
                 (encode-json-to-string '(:null))))
      "False")

There is a convenience function json-bool to make the keyword represenation:

(test json-bool
  (is (equal (json-bool t) '(:true)))
  (is (equal (json-bool 1) '(:true)))
  (is (equal (json-bool nil) '(:false))))

Also a related question is how to encode an empty list. As an empty
json object {}, empty json-list [] or as json-null? That can also be
handled with the explicit encoder.
Here is a sample how a complex json structure can be built (from
testencoder.lisp)

(sample-2-plists
 `(:object
   :method some-function
   :id  1
   :params (:list
            (:json "{\"id\":\"barId\",\"name\":\"bar\"}")
            (:true)
            (:list (:object "name"  a :id b))
            (:list (:object
                    :name  foo
                    :id  foo-id))
    )))
(correct-json "
  {\"method\":\"someFunction\",
    \"id\":1,\"params\":
         [{\"id\":\"barId\",\"name\":\"bar\"},
          true,
         [{\"name\":\"a\",\"id\":\"b\"}],
         [{\"name\":\"foo\",\"id\":\"fooId\"}]]}")

/Henrik Hjelte




More information about the cl-json-devel mailing list