[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: small seq function for json data

From: Helmut Eller
Subject: Re: small seq function for json data
Date: Sun, 16 Oct 2016 09:25:23 +0200
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/26.0.50 (gnu/linux)

On Sun, Oct 16 2016, Stefan Huchler wrote:

> accessing data coming from json requests can be a little bit anoying
> in elisp I think.

Yes, sounds familiar.

> So inspired by let-alist I wrote a more powerful version that supports
> also vector which is also used in json messages.
> (setq x '((foo . [((bar . "string of interest"))])))
> (defun sbit-seq-get (seq path)
>   (cond ((null path) seq)
>        ((listp seq)
>         (sbit-seq-get (cdr (assoc (car path) seq)) (cdr path))
>         )
>       ((vectorp seq)
>        (sbit-seq-get (elt seq (car path)) (cdr path))
>        )
>       (t seq)))
> (sbit-seq-get x '(foo 0 bar))

I've used this:

(defun json--ref (json key)
  (cl-etypecase key
    (symbol (let ((probe (assq key json)))
              (cond (probe (cdr probe))
                    (t (error "No entry for key: %S %S" key json)))))
    (integer (aref json key))))

(defun json-ref (json key &rest keys)
  (let ((tmp (json--ref json key)))
    (while keys
      (setq tmp (json--ref tmp (pop keys))))

(json-ref x 'foo 0 'bar)

A difference is that json--ref signals an error if the key is not in

> Does that make sense? Maybe integrate something similar to seq.el?

I think json.el would be the natural place; json objects are more like
trees than sequences.


reply via email to

[Prev in Thread] Current Thread [Next in Thread]