Emacs mode to edit JSON

Ryszard Szopa picture Ryszard Szopa · Jan 12, 2009 · Viewed 27.8k times · Source

Does anybody know a good Emacs mode to edit JSON? An app I am working on uses a JSON based communication protocol and having the data nicely indented and syntax-highlighted would help me a lot in the process of figuring it out.

Answer

jstevenco picture jstevenco · Oct 28, 2011

+1 for Josh's json-mode -- works well for me. I added

(defun beautify-json ()
  (interactive)
  (let ((b (if mark-active (min (point) (mark)) (point-min)))
        (e (if mark-active (max (point) (mark)) (point-max))))
    (shell-command-on-region b e
     "python -m json.tool" (current-buffer) t)))

and

(define-key json-mode-map (kbd "C-c C-f") 'beautify-json)

to json-mode.el to make the shell command invocation easier.

UPDATE: For those of you with a need/desire to do this with unicode, see my question here. The upshot is rather than using:

python -m json.tool

you will want to use

python -c 'import sys,json; data=json.loads(sys.stdin.read()); print json.dumps(data,sort_keys=True,indent=4).decode("unicode_escape").encode("utf8","replace")'

This both beautifies the JSON as well as preserving the original Unicode content.