Last active
November 26, 2017 07:30
-
-
Save jasonm23/7b60b3ba223fe4deb3da0263c3082315 to your computer and use it in GitHub Desktop.
DONT USE THIS - Use JSON Pointer https://github.com/syohex/emacs-json-pointer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;;; get-nested --- Fetch nodes from nested structures made by json.el | |
;;; Version: 0.1.0 | |
;;; Author: Jason Milkins jasonm23@gmail.com | |
;; | |
;;; Commentary: | |
;; | |
;; The alist/vector payload generated by json.el is very | |
;; handy, but Emacs Lisp doesn't (afaik?!) have nice ways to drill | |
;; down and cherry pick specific values from the tree. | |
;; | |
;; The examples in json.el don't really dive into this topic very | |
;; much, but let's expand on this a little bit. | |
;; | |
;; Using the oxford dictionary REST api as JSON source, let's say we | |
;; want to grab the etymology text. | |
;; | |
;; This lives on the following node (JS style) | |
;; results[0].lexicalEntries[0].entries[0].etymologies[0] | |
;; | |
;; To fetch from an alist/vector structure we'd need to do: | |
;; | |
;; (elt (cdr (cl-assoc 'etymologies | |
;; (elt (cdr (cl-assoc 'entries | |
;; (elt (cdr (cl-assoc 'lexicalEntries | |
;; (elt (cdr (cl-assoc 'results dictionary-payload)) | |
;; 0))) | |
;; 0))) | |
;; 0))) | |
;; 0) | |
;; | |
;; Even at 2 levels deep this is unpleasant and doing it like this is | |
;; quite naive. We could instead supply a lookup key and extract | |
;; the next piece of the structure, by wrapping up the (elt cdr assoc) | |
;; part. | |
;; | |
;; We can also wrap the lookup keys into a list and then reduce it | |
;; using the structure as the initial-value of the reduce. | |
;; | |
;; Note before we go on, please note this is a very early work in | |
;; progress, but it provides the functionality I wanted today. It | |
;; needs work to allow fetching from a specific element index in a | |
;; list. | |
;; | |
;; And so some code. | |
;; | |
;;; Code: | |
(eval-when-compile | |
(require 'cl)) | |
(defun --get (name structure) | |
"Fetch nested vector/alist from json.el by NAME from parent STRUCTURE." | |
(elt (cdr (cl-assoc name structure)) 0)) | |
(defun --nested-by (names structure) | |
"Fetch nested vector/alist from json.el using a list of NAMES in a STRUCTURE." | |
(cl-reduce (lambda (nested-structure name) | |
(--get name nested-structure)) | |
names :initial-value structure)) | |
(provide 'get-nested) | |
;;; get-nested.el ends here |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment