1 ;;; json.el --- JavaScript Object Notation parser / generator
3 ;; Copyright (C) 2006-2015 Free Software Foundation, Inc.
5 ;; Author: Edward O'Connor <ted@oconnor.cx>
7 ;; Keywords: convenience
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;; This is a library for parsing and generating JSON (JavaScript Object
29 ;; Learn all about JSON here: <URL:http://json.org/>.
31 ;; The user-serviceable entry points for the parser are the functions
32 ;; `json-read' and `json-read-from-string'. The encoder has a single
33 ;; entry point, `json-encode'.
35 ;; Since there are several natural representations of key-value pair
36 ;; mappings in elisp (alist, plist, hash-table), `json-read' allows you
37 ;; to specify which you'd prefer (see `json-object-type' and
38 ;; `json-array-type').
40 ;; Similarly, since `false' and `null' are distinct in JSON, you can
41 ;; distinguish them by binding `json-false' and `json-null' as desired.
45 ;; 2006-03-11 - Initial version.
46 ;; 2006-03-13 - Added JSON generation in addition to parsing. Various
47 ;; other cleanups, bugfixes, and improvements.
48 ;; 2006-12-29 - XEmacs support, from Aidan Kehoe <kehoea@parhasard.net>.
49 ;; 2008-02-21 - Installed in GNU Emacs.
50 ;; 2011-10-17 - Patch `json-alist-p' and `json-plist-p' to avoid recursion -tzz
51 ;; 2012-10-25 - Added pretty-printed reformatting -Ryan Crum (ryan@ryancrum.org)
59 (defvar json-object-type
'alist
60 "Type to convert JSON objects to.
61 Must be one of `alist', `plist', or `hash-table'. Consider let-binding
62 this around your call to `json-read' instead of `setq'ing it. Ordering
63 is maintained for `alist' and `plist', but not for `hash-table'.")
65 (defvar json-array-type
'vector
66 "Type to convert JSON arrays to.
67 Must be one of `vector' or `list'. Consider let-binding this around
68 your call to `json-read' instead of `setq'ing it.")
70 (defvar json-key-type nil
71 "Type to convert JSON keys to.
72 Must be one of `string', `symbol', `keyword', or nil.
74 If nil, `json-read' will guess the type based on the value of
77 If `json-object-type' is: nil will be interpreted as:
82 Note that values other than `string' might behave strangely for
83 Sufficiently Weird keys. Consider let-binding this around your call to
84 `json-read' instead of `setq'ing it.")
86 (defvar json-false
:json-false
87 "Value to use when reading JSON `false'.
88 If this has the same value as `json-null', you might not be able to tell
89 the difference between `false' and `null'. Consider let-binding this
90 around your call to `json-read' instead of `setq'ing it.")
93 "Value to use when reading JSON `null'.
94 If this has the same value as `json-false', you might not be able to
95 tell the difference between `false' and `null'. Consider let-binding
96 this around your call to `json-read' instead of `setq'ing it.")
98 (defvar json-encoding-separator
","
99 "Value to use as an element separator when encoding.")
101 (defvar json-encoding-default-indentation
" "
102 "The default indentation level for encoding.
103 Used only when `json-encoding-pretty-print' is non-nil.")
105 (defvar json--encoding-current-indentation
"\n"
106 "Internally used to keep track of the current indentation level of encoding.
107 Used only when `json-encoding-pretty-print' is non-nil.")
109 (defvar json-encoding-pretty-print nil
110 "If non-nil, then the output of `json-encode' will be pretty-printed.")
112 (defvar json-encoding-lisp-style-closings nil
113 "If non-nil, ] and } closings will be formatted lisp-style,
114 without indentation.")
116 (defvar json-encoding-object-sort-predicate nil
117 "Sorting predicate for JSON object keys during encoding.
118 If nil, no sorting is performed. Else, JSON object keys are
119 ordered by the specified sort predicate during encoding. For
120 instance, setting this to `string<' will have JSON object keys
121 ordered alphabetically.")
123 (defvar json-pre-element-read-function nil
124 "Function called (if non-nil) by `json-read-array' and
125 `json-read-object' right before reading a JSON array or object,
126 respectively. The function is called with one argument, which is
127 the current JSON key.")
129 (defvar json-post-element-read-function nil
130 "Function called (if non-nil) by `json-read-array' and
131 `json-read-object' right after reading a JSON array or object,
138 (defun json-join (strings separator
)
139 "Join STRINGS with SEPARATOR."
140 (mapconcat 'identity strings separator
))
142 (defun json-alist-p (list)
143 "Non-null if and only if LIST is an alist with simple keys."
145 (setq list
(if (and (consp (car list
))
151 (defun json-plist-p (list)
152 "Non-null if and only if LIST is a plist with keyword keys."
154 (setq list
(if (and (keywordp (car list
))
160 (defun json--plist-reverse (plist)
161 "Return a copy of PLIST in reverse order.
162 Unlike `reverse', this keeps the property-value pairs intact."
165 (let ((prop (pop plist
))
171 (defun json--plist-to-alist (plist)
172 "Return an alist of the property-value pairs in PLIST."
175 (let ((prop (pop plist
))
177 (push (cons prop val
) res
)))
180 (defmacro json--with-indentation
(body)
181 `(let ((json--encoding-current-indentation
182 (if json-encoding-pretty-print
183 (concat json--encoding-current-indentation
184 json-encoding-default-indentation
)
190 (defsubst json-advance
(&optional n
)
191 "Skip past the following N characters."
194 (defsubst json-peek
()
195 "Return the character at point."
196 (let ((char (char-after (point))))
197 (or char
:json-eof
)))
199 (defsubst json-pop
()
200 "Advance past the character at point, returning it."
201 (let ((char (json-peek)))
202 (if (eq char
:json-eof
)
203 (signal 'json-end-of-file nil
)
207 (defun json-skip-whitespace ()
208 "Skip past the whitespace at point."
209 (skip-chars-forward "\t\r\n\f\b "))
215 (define-error 'json-error
"Unknown JSON error")
216 (define-error 'json-readtable-error
"JSON readtable error" 'json-error
)
217 (define-error 'json-unknown-keyword
"Unrecognized keyword" 'json-error
)
218 (define-error 'json-number-format
"Invalid number format" 'json-error
)
219 (define-error 'json-string-escape
"Bad Unicode escape" 'json-error
)
220 (define-error 'json-string-format
"Bad string format" 'json-error
)
221 (define-error 'json-key-format
"Bad JSON object key" 'json-error
)
222 (define-error 'json-object-format
"Bad JSON object" 'json-error
)
223 (define-error 'json-end-of-file
"End of file while parsing JSON"
224 '(end-of-file json-error
))
230 (defvar json--path
'()
231 "Used internally by `json-path-to-position' to keep track of
232 the path during recursive calls to `json-read'.")
234 (defun json--record-path (key)
235 "Record the KEY to the current JSON path.
236 Used internally by `json-path-to-position'."
237 (push (cons (point) key
) json--path
))
239 (defun json--check-position (position)
240 "Check if the last parsed JSON structure passed POSITION.
241 Used internally by `json-path-to-position'."
242 (let ((start (caar json--path
)))
243 (when (< start position
(+ (point) 1))
244 (throw :json-path
(list :path
(nreverse (mapcar #'cdr json--path
))
246 :match-end
(point)))))
249 (defun json-path-to-position (position &optional string
)
250 "Return the path to the JSON element at POSITION.
252 When STRING is provided, return the path to the position in the
253 string, else to the position in the current buffer.
255 The return value is a property list with the following
258 :path -- A list of strings and numbers forming the path to
259 the JSON element at the given position. Strings
260 denote object names, while numbers denote array
263 :match-start -- Position where the matched JSON element begins.
265 :match-end -- Position where the matched JSON element ends.
267 This can for instance be useful to determine the path to a JSON
268 element in a deeply nested structure."
271 (goto-char (point-min)))
272 (let* ((json--path '())
273 (json-pre-element-read-function #'json--record-path
)
274 (json-post-element-read-function
275 (apply-partially #'json--check-position position
))
276 (path (catch :json-path
278 (json-read-from-string string
)
280 (when (plist-get path
:path
)
285 (defvar json-keywords
'("true" "false" "null")
286 "List of JSON keywords.")
290 (defun json-read-keyword (keyword)
291 "Read a JSON keyword at point.
292 KEYWORD is the keyword expected."
293 (unless (member keyword json-keywords
)
294 (signal 'json-unknown-keyword
(list keyword
)))
296 (unless (char-equal char
(json-peek))
297 (signal 'json-unknown-keyword
298 (list (save-excursion
300 (thing-at-point 'word
)))))
303 (unless (looking-at "\\(\\s-\\|[],}]\\|$\\)")
304 (signal 'json-unknown-keyword
305 (list (save-excursion
307 (thing-at-point 'word
)))))
308 (cond ((string-equal keyword
"true") t
)
309 ((string-equal keyword
"false") json-false
)
310 ((string-equal keyword
"null") json-null
)))
314 (defun json-encode-keyword (keyword)
315 "Encode KEYWORD as a JSON value."
316 (cond ((eq keyword t
) "true")
317 ((eq keyword json-false
) "false")
318 ((eq keyword json-null
) "null")))
324 (defun json-read-number (&optional sign
)
325 "Read the JSON number following point.
326 The optional SIGN argument is for internal use.
328 N.B.: Only numbers which can fit in Emacs Lisp's native number
329 representation will be parsed correctly."
330 ;; If SIGN is non-nil, the number is explicitly signed.
332 "\\([0-9]+\\)?\\(\\.[0-9]+\\)?\\([Ee][+-]?[0-9]+\\)?"))
333 (cond ((and (null sign
) (char-equal (json-peek) ?-
))
335 (- (json-read-number t
)))
336 ((and (null sign
) (char-equal (json-peek) ?
+))
338 (json-read-number t
))
339 ((and (looking-at number-regexp
)
340 (or (match-beginning 1)
341 (match-beginning 2)))
342 (goto-char (match-end 0))
343 (string-to-number (match-string 0)))
344 (t (signal 'json-number-format
(list (point)))))))
348 (defun json-encode-number (number)
349 "Return a JSON representation of NUMBER."
350 (format "%s" number
))
354 (defvar json-special-chars
362 "Characters which are escaped in JSON, with their elisp counterparts.")
366 (defun json-read-escaped-char ()
367 "Read the JSON string escaped character at point."
370 (let* ((char (json-pop))
371 (special (assq char json-special-chars
)))
373 (special (cdr special
))
374 ((not (eq char ?u
)) char
)
375 ((looking-at "[0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f]")
376 (let ((hex (match-string 0)))
378 (string-to-number hex
16)))
380 (signal 'json-string-escape
(list (point)))))))
382 (defun json-read-string ()
383 "Read the JSON string at point."
384 (unless (char-equal (json-peek) ?
\")
385 (signal 'json-string-format
(list "doesn't start with `\"'!")))
388 (let ((characters '())
390 (while (not (char-equal char ?
\"))
391 (push (if (char-equal char ?
\\)
392 (json-read-escaped-char)
395 (setq char
(json-peek)))
399 (apply 'string
(nreverse characters
))
404 (defun json-encode-string (string)
405 "Return a JSON representation of STRING."
406 ;; Reimplement the meat of `replace-regexp-in-string', for
407 ;; performance (bug#20154).
408 (let ((l (length string
))
411 ;; Only escape quotation mark, backslash and the control
412 ;; characters U+0000 to U+001F (RFC 4627, ECMA-404).
413 (while (setq mb
(string-match "[\"\\[:cntrl:]]" string start
))
414 (let* ((c (aref string mb
))
415 (special (rassq c json-special-chars
)))
416 (push (substring string start mb
) res
)
418 ;; Special JSON character (\n, \r, etc.).
419 (string ?
\\ (car special
))
420 ;; Fallback: UCS code point in \uNNNN form.
421 (format "\\u%04x" c
))
423 (setq start
(1+ mb
))))
424 (push (substring string start l
) res
)
426 (apply #'concat
"\"" (nreverse res
))))
428 (defun json-encode-key (object)
429 "Return a JSON representation of OBJECT.
430 If the resulting JSON object isn't a valid JSON object key,
431 this signals `json-key-format'."
432 (let ((encoded (json-encode object
)))
433 (unless (stringp (json-read-from-string encoded
))
434 (signal 'json-key-format
(list object
)))
439 (defun json-new-object ()
440 "Create a new Elisp object corresponding to a JSON object.
441 Please see the documentation of `json-object-type'."
442 (cond ((eq json-object-type
'hash-table
)
443 (make-hash-table :test
'equal
))
447 (defun json-add-to-object (object key value
)
448 "Add a new KEY -> VALUE association to OBJECT.
449 Returns the updated object, which you should save, e.g.:
450 (setq obj (json-add-to-object obj \"foo\" \"bar\"))
451 Please see the documentation of `json-object-type' and `json-key-type'."
453 (if (eq json-key-type nil
)
454 (cdr (assq json-object-type
'((hash-table . string
)
459 (cond ((eq json-key-type
'string
)
461 ((eq json-key-type
'symbol
)
463 ((eq json-key-type
'keyword
)
464 (intern (concat ":" key
)))))
465 (cond ((eq json-object-type
'hash-table
)
466 (puthash key value object
)
468 ((eq json-object-type
'alist
)
469 (cons (cons key value
) object
))
470 ((eq json-object-type
'plist
)
471 (cons key
(cons value object
))))))
473 ;; JSON object parsing
475 (defun json-read-object ()
476 "Read the JSON object at point."
479 (json-skip-whitespace)
480 ;; read key/value pairs until "}"
481 (let ((elements (json-new-object))
483 (while (not (char-equal (json-peek) ?
}))
484 (json-skip-whitespace)
485 (setq key
(json-read-string))
486 (json-skip-whitespace)
487 (if (char-equal (json-peek) ?
:)
489 (signal 'json-object-format
(list ":" (json-peek))))
490 (json-skip-whitespace)
491 (when json-pre-element-read-function
492 (funcall json-pre-element-read-function key
))
493 (setq value
(json-read))
494 (when json-post-element-read-function
495 (funcall json-post-element-read-function
))
496 (setq elements
(json-add-to-object elements key value
))
497 (json-skip-whitespace)
498 (unless (char-equal (json-peek) ?
})
499 (if (char-equal (json-peek) ?
,)
501 (signal 'json-object-format
(list "," (json-peek))))))
504 (pcase json-object-type
505 (`alist
(nreverse elements
))
506 (`plist
(json--plist-reverse elements
))
509 ;; Hash table encoding
511 (defun json-encode-hash-table (hash-table)
512 "Return a JSON representation of HASH-TABLE."
513 (if json-encoding-object-sort-predicate
514 (json-encode-alist (map-into hash-table
'list
))
518 (json--with-indentation
522 (if json-encoding-pretty-print
525 json--encoding-current-indentation
531 json-encoding-separator
)
532 (if (or (not json-encoding-pretty-print
)
533 json-encoding-lisp-style-closings
)
535 json--encoding-current-indentation
))))
537 ;; List encoding (including alists and plists)
539 (defun json-encode-alist (alist)
540 "Return a JSON representation of ALIST."
541 (when json-encoding-object-sort-predicate
543 (sort alist
(lambda (a b
)
544 (funcall json-encoding-object-sort-predicate
548 (json--with-indentation
549 (mapcar (lambda (cons)
550 (format (if json-encoding-pretty-print
553 json--encoding-current-indentation
554 (json-encode-key (car cons
))
555 (json-encode (cdr cons
))))
557 json-encoding-separator
)
558 (if (or (not json-encoding-pretty-print
)
559 json-encoding-lisp-style-closings
)
561 json--encoding-current-indentation
)))
563 (defun json-encode-plist (plist)
564 "Return a JSON representation of PLIST."
565 (if json-encoding-object-sort-predicate
566 (json-encode-alist (json--plist-to-alist plist
))
568 (json--with-indentation
571 json--encoding-current-indentation
572 (json-encode-key (car plist
))
573 (if json-encoding-pretty-print
576 (json-encode (cadr plist
)))
578 (setq plist
(cddr plist
))))
580 (json-join (nreverse result
) json-encoding-separator
)
581 (if (and json-encoding-pretty-print
582 (not json-encoding-lisp-style-closings
))
583 json--encoding-current-indentation
587 (defun json-encode-list (list)
588 "Return a JSON representation of LIST.
589 Tries to DWIM: simple lists become JSON arrays, while alists and plists
590 become JSON objects."
591 (cond ((null list
) "null")
592 ((json-alist-p list
) (json-encode-alist list
))
593 ((json-plist-p list
) (json-encode-plist list
))
594 ((listp list
) (json-encode-array list
))
596 (signal 'json-error
(list list
)))))
602 (defun json-read-array ()
603 "Read the JSON array at point."
606 (json-skip-whitespace)
607 ;; read values until "]"
609 (while (not (char-equal (json-peek) ?\
]))
610 (json-skip-whitespace)
611 (when json-pre-element-read-function
612 (funcall json-pre-element-read-function
(length elements
)))
613 (push (json-read) elements
)
614 (when json-post-element-read-function
615 (funcall json-post-element-read-function
))
616 (json-skip-whitespace)
617 (unless (char-equal (json-peek) ?\
])
618 (if (char-equal (json-peek) ?
,)
620 (signal 'json-error
(list 'bleah
)))))
623 (apply json-array-type
(nreverse elements
))))
627 (defun json-encode-array (array)
628 "Return a JSON representation of ARRAY."
629 (if (and json-encoding-pretty-print
630 (> (length array
) 0))
632 (json--with-indentation
633 (concat (format "[%s" json--encoding-current-indentation
)
634 (json-join (mapcar 'json-encode array
)
636 json-encoding-separator
637 json--encoding-current-indentation
))))
639 (if json-encoding-lisp-style-closings
641 json--encoding-current-indentation
)))
643 (mapconcat 'json-encode array json-encoding-separator
)
650 (defvar json-readtable
652 '((?t json-read-keyword
"true")
653 (?f json-read-keyword
"false")
654 (?n json-read-keyword
"null")
655 (?
{ json-read-object
)
656 (?\
[ json-read-array
)
657 (?
\" json-read-string
))))
659 (push (list char
'json-read-number
) table
))
660 '(?- ?
+ ?. ?
0 ?
1 ?
2 ?
3 ?
4 ?
5 ?
6 ?
7 ?
8 ?
9))
662 "Readtable for JSON reader.")
665 "Parse and return the JSON object following point.
666 Advances point just past JSON object."
667 (json-skip-whitespace)
668 (let ((char (json-peek)))
669 (if (not (eq char
:json-eof
))
670 (let ((record (cdr (assq char json-readtable
))))
671 (if (functionp (car record
))
672 (apply (car record
) (cdr record
))
673 (signal 'json-readtable-error record
)))
674 (signal 'json-end-of-file nil
))))
676 ;; Syntactic sugar for the reader
678 (defun json-read-from-string (string)
679 "Read the JSON object contained in STRING and return it."
682 (goto-char (point-min))
685 (defun json-read-file (file)
686 "Read the first JSON object contained in FILE and return it."
688 (insert-file-contents file
)
689 (goto-char (point-min))
696 (defun json-encode (object)
697 "Return a JSON representation of OBJECT as a string."
698 (cond ((memq object
(list t json-null json-false
))
699 (json-encode-keyword object
))
700 ((stringp object
) (json-encode-string object
))
701 ((keywordp object
) (json-encode-string
702 (substring (symbol-name object
) 1)))
703 ((symbolp object
) (json-encode-string
704 (symbol-name object
)))
705 ((numberp object
) (json-encode-number object
))
706 ((arrayp object
) (json-encode-array object
))
707 ((hash-table-p object
) (json-encode-hash-table object
))
708 ((listp object
) (json-encode-list object
))
709 (t (signal 'json-error
(list object
)))))
713 (defun json-pretty-print-buffer ()
714 "Pretty-print current buffer."
716 (json-pretty-print (point-min) (point-max)))
718 (defun json-pretty-print (begin end
)
719 "Pretty-print selected region."
722 (let ((json-encoding-pretty-print t
)
723 ;; Ensure that ordering is maintained
724 (json-object-type 'alist
)
725 (txt (delete-and-extract-region begin end
)))
726 (insert (json-encode (json-read-from-string txt
))))))
728 (defun json-pretty-print-buffer-ordered ()
729 "Pretty-print current buffer with object keys ordered."
731 (let ((json-encoding-object-sort-predicate 'string
<))
732 (json-pretty-print-buffer)))
734 (defun json-pretty-print-ordered (begin end
)
735 "Pretty-print the region with object keys ordered."
737 (let ((json-encoding-object-sort-predicate 'string
<))
738 (json-pretty-print begin end
)))
742 ;;; json.el ends here