0

To effectively use a service's API, I'm leveraging json-read to turn the JSON response into an understandable data structure:

(let ((json-object-type 'alist)
      (json-array-type  'list)
      (json-key-type    'symbol)
      (json-false       nil)
      (json-null        nil))
  (json-read))

This works great, but gives me a bunch of garbage that I don't care about.

I want a function keep-structure that works through this alist and filters out all of the junk:

(keep-structure '((owner login) name)
                '((owner (login . "octocat") (avatar . "blah"))
                  (name . "Hello-World")
                  (some-url . "https://some-domain")
                  (stars . 42)))

;; => ((owner (login . "octocat"))
       (name . "Hello-World"))
2

Recursion for the win.

(defun json-filter-paths (json paths)
  (mapcar (lambda (elt)
            (if (consp elt)
                (cons (car elt)
                      (json-filter-paths (cdr (assoc (car elt) json)) (cdr elt)))
              (cons elt (cdr (assoc elt json)))))
          paths))

(json-filter-paths'((owner (login . "octocat") (avatar . "blah")
                           (meta (x . "42") (y . "43")))
                    (name . "Hello-World")
                    (some-url . "https://some-domain")
                    (stars . 42))
                  '(name (owner login (meta x))))
;; ((name . "Hello-World") (owner (login . "octocat") (meta (x . "42"))))
  • Oooh, that's much nicer-looking :-) – Sean Allred Feb 25 '17 at 21:15
0

Take this for a spin:

(require 'dash)  ;; also needs emacs-25 for `if-let'
(defun keep-structure (structure object)
  (let* ((only-tops (mapcar (lambda (el)
                              (if (consp el) (car el) el))
                            structure))
         (top-pass (--filter (memq (car it) only-tops)
                             object)))
    (mapcar
     (lambda (subobj)
       (if-let ((substructure
                 (cdar (--filter (and (consp it)
                                      (eq (car subobj)
                                          (car it)))
                                 structure))))
           (cons (car subobj)
                 (keep-structure substructure (cdr subobj)))
         subobj))
     top-pass)))

(keep-structure '((owner login) name)
                '((owner (login . "octocat") (avatar . "blah"))
                  (name . "Hello-World")
                  (some-url . "https://some-domain")
                  (stars . 42)))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.