Now try to get the data in it. In JS, you can get any data in JSON easily with data.key[n]...., but json.el seems not to provide an easy way to get data iterately from it; and a lot of duplicated (cdr (assq 'key data)) and (aref data 0) make code hardly readable.
So let’s write a function:
Iteration Way
1 2 3 4 5 6 7
(defun json-getdata (data&rest args) (do ((i0 (1+ i))) ((> i (1- (length args))) data) (cond ((symbolp (elt args i)) (setq data (cdr (assq (elt args i) data)))) ((numberp (elt args i)) (setq data (aref data (elt args i)))))))
Now you can get data from JSON like this:
1
(json-getdata data 'heteronyms 0 'definitions)
It’s nearly the equivalent of (in JS):
1
data.heteronyms[0].definitions
Use loop to get n data in vector, and collect all results as a list (like mapcar):
1 2
(loop for i from 0 to 4 collect (json-getdata data 'heteronyms 0 'definitions i))
Recursive Way
At first, I tried to write this function in recursive way. However I just couldn’t done this mission which nearly made me insane. Now I found that’s because my unfamiliarity of two concepts: &rest and apply:
Will goes wrong. Because it will be called (recursively) like this:
1
(json-get DEEPTH-2-DATA ('key2 'key3))
instead of:
1
(json-get DEEPTH-2-DATA 'key2 'key3)
So apply is needed:
1 2 3
(apply #'+ '(123)) => 6;the last argument of `apply' should be a list (apply #'+ 12 '(123)) => 9 (funcall #'+ 123) => 6;Don't confound `funcall' with `apply' !!!!!!!