Introducing json.el (original) (raw)
JSON is a lightweight data interchange format based on a subset of JavaScript. You can read all about JSON at json.org.json.el is a JSON parser and generator for Emacs Lisp, which can produce an Emacs Lisp data structure from a JSON object and vice-versa. It’s been Included with Emacs since February 2008.
Using it is pretty straightforward; here are some examples.
(require 'json) json
JSON's primitive values are strings, numbers, and the keywordstrue, false, and null.
(json-read-from-string "true") t(json-encode t) "true"(json-read-from-string "4.5") 4.5(json-read-from-string "\\"foo\\"") "foo"
JSON's compound values are arrays and dictionaries.
(json-read-from-string "[true, 4.5]") [t 4.5](json-read-from-string "{\\"foo\\": true}") ((foo . t))
Notice that we read the JSON array as a lisp vector and the JSON dictionary as an alist. We could just have read the array as a list, and the dictionary as a plist or hashtable. json.el allows for all of these representations. (Also, note that the alist keys are symbols; we could read these as keywords or strings.)
- dictionary-as-plist:
(let ((json-object-type 'plist)) (json-read-from-string "{\\"foo\\": true}")) (:foo t)- key-as-string:
(let ((json-key-type 'string)) (json-read-from-string "{\\"foo\\": true}")) (("foo" . t))- dictionary-as-hashtable:
- `(let ((json-object-type 'hash-table))
(json-read-from-string "{\"foo\": true}"))
#<hash-table 'equal nil 1/65 0x314f800>
- (gethash "foo" *)
t`
json.el generally does the right thing when encoding idiomatic lisp data structures:
(json-encode '(1 2 3)) "[1, 2, 3]"(json-encode '(:foo 1 :bar 2 :baz 3)) "{\\"foo\\":1, \\"bar\\":2, \\"baz\\":3}"