Skip to content

Instantly share code, notes, and snippets.

@fiddlerwoaroof
Created December 14, 2021 23:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fiddlerwoaroof/970a81bec97c063196f815f21799d3ba to your computer and use it in GitHub Desktop.
Save fiddlerwoaroof/970a81bec97c063196f815f21799d3ba to your computer and use it in GitHub Desktop.
JSON narrowing commands for emacs

If you load this in emacs and open a file with a JSON buffer, the command M-x fwoar/dive will let you type a key and replace the contents of the buffer with either the value of the corresponding key (if the JSON value of the buffer is an object) or an array of the corresponding value for each object in an array (if the JSON value of the buffer is an array). M-x fwoar/return will pop the most recently used key off the stack and replace the buffer contents with the corresponding contents of the original JSON object.

This is mainly a prototype, but it's already useful for quickly zooming in on large JSON documents.

(defvar-local fwoar/json-nav--data nil)
(defvar-local fwoar/json-nav--path nil)
(defun fwoar/json--init-data ()
(unless data
(save-excursion
(point-min)
(setq-local fwoar/json-nav--data (json-parse-buffer)))))
(defun fwoar/dive (s)
(interactive "M")
(fwoar/json--init-data)
(setq-local fwoar/json-nav--path (cons s fwoar/json-nav--path))
(setf (buffer-string)
(json-serialize (loop with cur = data for key in (reverse fwoar/json-nav--path)
do
(setf cur
(typecase cur
(vector (message "vector")(coerce (funcall (fwoar/over
(fwoar/key key))
cur)
'vector))
(t (funcall (fwoar/key key) cur))))
finally (return cur))))
(json-pretty-print-buffer)
(point-min))
(defun fwoar/return ()
(interactive)
(fwoar/json--init-data)
(setq-local fwoar/json-nav--path (cdr fwoar/json-nav--path))
(setf (buffer-string)
(json-serialize (loop with cur = data for key in (reverse fwoar/json-nav--path)
do
(setf cur
(typecase cur
(vector (message "vector")(coerce (funcall (fwoar/over
(fwoar/key key))
cur)
'vector))
(t (funcall (fwoar/key key) cur))))
finally (return cur))))
(json-pretty-print-buffer)
(point-min))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment