Merge branch 'master' into comment-cache
[emacs.git] / lisp / json.el
blobb2ac356641b87edae97b9ce4227895ca87f0e299
1 ;;; json.el --- JavaScript Object Notation parser / generator -*- lexical-binding: t -*-
3 ;; Copyright (C) 2006-2017 Free Software Foundation, Inc.
5 ;; Author: Edward O'Connor <ted@oconnor.cx>
6 ;; Version: 1.4
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/>.
24 ;;; Commentary:
26 ;; This is a library for parsing and generating JSON (JavaScript Object
27 ;; Notation).
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.
43 ;;; History:
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)
53 ;;; Code:
55 (require 'map)
57 ;; Parameters
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
75 `json-object-type':
77 If `json-object-type' is: nil will be interpreted as:
78 `hash-table' `string'
79 `alist' `symbol'
80 `plist' `keyword'
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.")
92 (defvar json-null nil
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,
132 respectively.")
136 ;;; Utilities
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."
144 (while (consp list)
145 (setq list (if (and (consp (car list))
146 (atom (caar list)))
147 (cdr list)
148 'not-alist)))
149 (null list))
151 (defun json-plist-p (list)
152 "Non-null if and only if LIST is a plist with keyword keys."
153 (while (consp list)
154 (setq list (if (and (keywordp (car list))
155 (consp (cdr list)))
156 (cddr list)
157 'not-plist)))
158 (null 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."
163 (let (res)
164 (while plist
165 (let ((prop (pop plist))
166 (val (pop plist)))
167 (push val res)
168 (push prop res)))
169 res))
171 (defun json--plist-to-alist (plist)
172 "Return an alist of the property-value pairs in PLIST."
173 (let (res)
174 (while plist
175 (let ((prop (pop plist))
176 (val (pop plist)))
177 (push (cons prop val) res)))
178 (nreverse 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)
185 "")))
186 ,body))
188 ;; Reader utilities
190 (defsubst json-advance (&optional n)
191 "Skip past the following N characters."
192 (forward-char n))
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)
204 (json-advance)
205 char)))
207 (defun json-skip-whitespace ()
208 "Skip past the whitespace at point."
209 (skip-chars-forward "\t\r\n\f\b "))
213 ;; Error conditions
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))
228 ;;; Paths
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))
245 :match-start start
246 :match-end (point)))))
247 (pop json--path))
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
256 properties:
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
261 indexes.
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."
269 (save-excursion
270 (unless string
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
277 (if string
278 (json-read-from-string string)
279 (json-read)))))
280 (when (plist-get path :path)
281 path))))
283 ;;; Keywords
285 (defvar json-keywords '("true" "false" "null")
286 "List of JSON keywords.")
288 ;; Keyword parsing
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)))
295 (mapc (lambda (char)
296 (unless (char-equal char (json-peek))
297 (signal 'json-unknown-keyword
298 (list (save-excursion
299 (backward-word-strictly 1)
300 (thing-at-point 'word)))))
301 (json-advance))
302 keyword)
303 (unless (looking-at "\\(\\s-\\|[],}]\\|$\\)")
304 (signal 'json-unknown-keyword
305 (list (save-excursion
306 (backward-word-strictly 1)
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)))
312 ;; Keyword encoding
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")))
320 ;;; Numbers
322 ;; Number parsing
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.
331 (let ((number-regexp
332 "\\([0-9]+\\)?\\(\\.[0-9]+\\)?\\([Ee][+-]?[0-9]+\\)?"))
333 (cond ((and (null sign) (char-equal (json-peek) ?-))
334 (json-advance)
335 (- (json-read-number t)))
336 ((and (null sign) (char-equal (json-peek) ?+))
337 (json-advance)
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)))))))
346 ;; Number encoding
348 (defun json-encode-number (number)
349 "Return a JSON representation of NUMBER."
350 (format "%s" number))
352 ;;; Strings
354 (defvar json-special-chars
355 '((?\" . ?\")
356 (?\\ . ?\\)
357 (?b . ?\b)
358 (?f . ?\f)
359 (?n . ?\n)
360 (?r . ?\r)
361 (?t . ?\t))
362 "Characters which are escaped in JSON, with their elisp counterparts.")
364 ;; String parsing
366 (defun json--decode-utf-16-surrogates (high low)
367 "Return the code point represented by the UTF-16 surrogates HIGH and LOW."
368 (+ (lsh (- high #xD800) 10) (- low #xDC00) #x10000))
370 (defun json-read-escaped-char ()
371 "Read the JSON string escaped character at point."
372 ;; Skip over the '\'
373 (json-advance)
374 (let* ((char (json-pop))
375 (special (assq char json-special-chars)))
376 (cond
377 (special (cdr special))
378 ((not (eq char ?u)) char)
379 ;; Special-case UTF-16 surrogate pairs,
380 ;; cf. https://tools.ietf.org/html/rfc7159#section-7. Note that
381 ;; this clause overlaps with the next one and therefore has to
382 ;; come first.
383 ((looking-at
384 (rx (group (any "Dd") (any "89ABab") (= 2 (any "0-9A-Fa-f")))
385 "\\u" (group (any "Dd") (any "C-Fc-f") (= 2 (any "0-9A-Fa-f")))))
386 (json-advance 10)
387 (json--decode-utf-16-surrogates
388 (string-to-number (match-string 1) 16)
389 (string-to-number (match-string 2) 16)))
390 ((looking-at "[0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f]")
391 (let ((hex (match-string 0)))
392 (json-advance 4)
393 (string-to-number hex 16)))
395 (signal 'json-string-escape (list (point)))))))
397 (defun json-read-string ()
398 "Read the JSON string at point."
399 (unless (char-equal (json-peek) ?\")
400 (signal 'json-string-format (list "doesn't start with `\"'!")))
401 ;; Skip over the '"'
402 (json-advance)
403 (let ((characters '())
404 (char (json-peek)))
405 (while (not (char-equal char ?\"))
406 (push (if (char-equal char ?\\)
407 (json-read-escaped-char)
408 (json-pop))
409 characters)
410 (setq char (json-peek)))
411 ;; Skip over the '"'
412 (json-advance)
413 (if characters
414 (apply 'string (nreverse characters))
415 "")))
417 ;; String encoding
419 (defun json-encode-string (string)
420 "Return a JSON representation of STRING."
421 ;; Reimplement the meat of `replace-regexp-in-string', for
422 ;; performance (bug#20154).
423 (let ((l (length string))
424 (start 0)
425 res mb)
426 ;; Only escape quotation mark, backslash and the control
427 ;; characters U+0000 to U+001F (RFC 4627, ECMA-404).
428 (while (setq mb (string-match "[\"\\[:cntrl:]]" string start))
429 (let* ((c (aref string mb))
430 (special (rassq c json-special-chars)))
431 (push (substring string start mb) res)
432 (push (if special
433 ;; Special JSON character (\n, \r, etc.).
434 (string ?\\ (car special))
435 ;; Fallback: UCS code point in \uNNNN form.
436 (format "\\u%04x" c))
437 res)
438 (setq start (1+ mb))))
439 (push (substring string start l) res)
440 (push "\"" res)
441 (apply #'concat "\"" (nreverse res))))
443 (defun json-encode-key (object)
444 "Return a JSON representation of OBJECT.
445 If the resulting JSON object isn't a valid JSON object key,
446 this signals `json-key-format'."
447 (let ((encoded (json-encode object)))
448 (unless (stringp (json-read-from-string encoded))
449 (signal 'json-key-format (list object)))
450 encoded))
452 ;;; JSON Objects
454 (defun json-new-object ()
455 "Create a new Elisp object corresponding to a JSON object.
456 Please see the documentation of `json-object-type'."
457 (cond ((eq json-object-type 'hash-table)
458 (make-hash-table :test 'equal))
460 ())))
462 (defun json-add-to-object (object key value)
463 "Add a new KEY -> VALUE association to OBJECT.
464 Returns the updated object, which you should save, e.g.:
465 (setq obj (json-add-to-object obj \"foo\" \"bar\"))
466 Please see the documentation of `json-object-type' and `json-key-type'."
467 (let ((json-key-type
468 (if (eq json-key-type nil)
469 (cdr (assq json-object-type '((hash-table . string)
470 (alist . symbol)
471 (plist . keyword))))
472 json-key-type)))
473 (setq key
474 (cond ((eq json-key-type 'string)
475 key)
476 ((eq json-key-type 'symbol)
477 (intern key))
478 ((eq json-key-type 'keyword)
479 (intern (concat ":" key)))))
480 (cond ((eq json-object-type 'hash-table)
481 (puthash key value object)
482 object)
483 ((eq json-object-type 'alist)
484 (cons (cons key value) object))
485 ((eq json-object-type 'plist)
486 (cons key (cons value object))))))
488 ;; JSON object parsing
490 (defun json-read-object ()
491 "Read the JSON object at point."
492 ;; Skip over the "{"
493 (json-advance)
494 (json-skip-whitespace)
495 ;; read key/value pairs until "}"
496 (let ((elements (json-new-object))
497 key value)
498 (while (not (char-equal (json-peek) ?}))
499 (json-skip-whitespace)
500 (setq key (json-read-string))
501 (json-skip-whitespace)
502 (if (char-equal (json-peek) ?:)
503 (json-advance)
504 (signal 'json-object-format (list ":" (json-peek))))
505 (json-skip-whitespace)
506 (when json-pre-element-read-function
507 (funcall json-pre-element-read-function key))
508 (setq value (json-read))
509 (when json-post-element-read-function
510 (funcall json-post-element-read-function))
511 (setq elements (json-add-to-object elements key value))
512 (json-skip-whitespace)
513 (unless (char-equal (json-peek) ?})
514 (if (char-equal (json-peek) ?,)
515 (json-advance)
516 (signal 'json-object-format (list "," (json-peek))))))
517 ;; Skip over the "}"
518 (json-advance)
519 (pcase json-object-type
520 (`alist (nreverse elements))
521 (`plist (json--plist-reverse elements))
522 (_ elements))))
524 ;; Hash table encoding
526 (defun json-encode-hash-table (hash-table)
527 "Return a JSON representation of HASH-TABLE."
528 (if json-encoding-object-sort-predicate
529 (json-encode-alist (map-into hash-table 'list))
530 (format "{%s%s}"
531 (json-join
532 (let (r)
533 (json--with-indentation
534 (maphash
535 (lambda (k v)
536 (push (format
537 (if json-encoding-pretty-print
538 "%s%s: %s"
539 "%s%s:%s")
540 json--encoding-current-indentation
541 (json-encode-key k)
542 (json-encode v))
544 hash-table))
546 json-encoding-separator)
547 (if (or (not json-encoding-pretty-print)
548 json-encoding-lisp-style-closings)
550 json--encoding-current-indentation))))
552 ;; List encoding (including alists and plists)
554 (defun json-encode-alist (alist)
555 "Return a JSON representation of ALIST."
556 (when json-encoding-object-sort-predicate
557 (setq alist
558 (sort alist (lambda (a b)
559 (funcall json-encoding-object-sort-predicate
560 (car a) (car b))))))
561 (format "{%s%s}"
562 (json-join
563 (json--with-indentation
564 (mapcar (lambda (cons)
565 (format (if json-encoding-pretty-print
566 "%s%s: %s"
567 "%s%s:%s")
568 json--encoding-current-indentation
569 (json-encode-key (car cons))
570 (json-encode (cdr cons))))
571 alist))
572 json-encoding-separator)
573 (if (or (not json-encoding-pretty-print)
574 json-encoding-lisp-style-closings)
576 json--encoding-current-indentation)))
578 (defun json-encode-plist (plist)
579 "Return a JSON representation of PLIST."
580 (if json-encoding-object-sort-predicate
581 (json-encode-alist (json--plist-to-alist plist))
582 (let (result)
583 (json--with-indentation
584 (while plist
585 (push (concat
586 json--encoding-current-indentation
587 (json-encode-key (car plist))
588 (if json-encoding-pretty-print
589 ": "
590 ":")
591 (json-encode (cadr plist)))
592 result)
593 (setq plist (cddr plist))))
594 (concat "{"
595 (json-join (nreverse result) json-encoding-separator)
596 (if (and json-encoding-pretty-print
597 (not json-encoding-lisp-style-closings))
598 json--encoding-current-indentation
600 "}"))))
602 (defun json-encode-list (list)
603 "Return a JSON representation of LIST.
604 Tries to DWIM: simple lists become JSON arrays, while alists and plists
605 become JSON objects."
606 (cond ((null list) "null")
607 ((json-alist-p list) (json-encode-alist list))
608 ((json-plist-p list) (json-encode-plist list))
609 ((listp list) (json-encode-array list))
611 (signal 'json-error (list list)))))
613 ;;; Arrays
615 ;; Array parsing
617 (defun json-read-array ()
618 "Read the JSON array at point."
619 ;; Skip over the "["
620 (json-advance)
621 (json-skip-whitespace)
622 ;; read values until "]"
623 (let (elements)
624 (while (not (char-equal (json-peek) ?\]))
625 (json-skip-whitespace)
626 (when json-pre-element-read-function
627 (funcall json-pre-element-read-function (length elements)))
628 (push (json-read) elements)
629 (when json-post-element-read-function
630 (funcall json-post-element-read-function))
631 (json-skip-whitespace)
632 (unless (char-equal (json-peek) ?\])
633 (if (char-equal (json-peek) ?,)
634 (json-advance)
635 (signal 'json-error (list 'bleah)))))
636 ;; Skip over the "]"
637 (json-advance)
638 (apply json-array-type (nreverse elements))))
640 ;; Array encoding
642 (defun json-encode-array (array)
643 "Return a JSON representation of ARRAY."
644 (if (and json-encoding-pretty-print
645 (> (length array) 0))
646 (concat
647 (json--with-indentation
648 (concat (format "[%s" json--encoding-current-indentation)
649 (json-join (mapcar 'json-encode array)
650 (format "%s%s"
651 json-encoding-separator
652 json--encoding-current-indentation))))
653 (format "%s]"
654 (if json-encoding-lisp-style-closings
656 json--encoding-current-indentation)))
657 (concat "["
658 (mapconcat 'json-encode array json-encoding-separator)
659 "]")))
663 ;;; JSON reader.
665 (defvar json-readtable
666 (let ((table
667 '((?t json-read-keyword "true")
668 (?f json-read-keyword "false")
669 (?n json-read-keyword "null")
670 (?{ json-read-object)
671 (?\[ json-read-array)
672 (?\" json-read-string))))
673 (mapc (lambda (char)
674 (push (list char 'json-read-number) table))
675 '(?- ?+ ?. ?0 ?1 ?2 ?3 ?4 ?5 ?6 ?7 ?8 ?9))
676 table)
677 "Readtable for JSON reader.")
679 (defun json-read ()
680 "Parse and return the JSON object following point.
681 Advances point just past JSON object."
682 (json-skip-whitespace)
683 (let ((char (json-peek)))
684 (if (not (eq char :json-eof))
685 (let ((record (cdr (assq char json-readtable))))
686 (if (functionp (car record))
687 (apply (car record) (cdr record))
688 (signal 'json-readtable-error record)))
689 (signal 'json-end-of-file nil))))
691 ;; Syntactic sugar for the reader
693 (defun json-read-from-string (string)
694 "Read the JSON object contained in STRING and return it."
695 (with-temp-buffer
696 (insert string)
697 (goto-char (point-min))
698 (json-read)))
700 (defun json-read-file (file)
701 "Read the first JSON object contained in FILE and return it."
702 (with-temp-buffer
703 (insert-file-contents file)
704 (goto-char (point-min))
705 (json-read)))
709 ;;; JSON encoder
711 (defun json-encode (object)
712 "Return a JSON representation of OBJECT as a string."
713 (cond ((memq object (list t json-null json-false))
714 (json-encode-keyword object))
715 ((stringp object) (json-encode-string object))
716 ((keywordp object) (json-encode-string
717 (substring (symbol-name object) 1)))
718 ((symbolp object) (json-encode-string
719 (symbol-name object)))
720 ((numberp object) (json-encode-number object))
721 ((arrayp object) (json-encode-array object))
722 ((hash-table-p object) (json-encode-hash-table object))
723 ((listp object) (json-encode-list object))
724 (t (signal 'json-error (list object)))))
726 ;; Pretty printing
728 (defun json-pretty-print-buffer ()
729 "Pretty-print current buffer."
730 (interactive)
731 (json-pretty-print (point-min) (point-max)))
733 (defun json-pretty-print (begin end)
734 "Pretty-print selected region."
735 (interactive "r")
736 (atomic-change-group
737 (let ((json-encoding-pretty-print t)
738 ;; Ensure that ordering is maintained
739 (json-object-type 'alist)
740 (txt (delete-and-extract-region begin end)))
741 (insert (json-encode (json-read-from-string txt))))))
743 (defun json-pretty-print-buffer-ordered ()
744 "Pretty-print current buffer with object keys ordered."
745 (interactive)
746 (let ((json-encoding-object-sort-predicate 'string<))
747 (json-pretty-print-buffer)))
749 (defun json-pretty-print-ordered (begin end)
750 "Pretty-print the region with object keys ordered."
751 (interactive "r")
752 (let ((json-encoding-object-sort-predicate 'string<))
753 (json-pretty-print begin end)))
755 (provide 'json)
757 ;;; json.el ends here