5

Say I have a list of names with ids, in JSON:

(let ((json-object-type 'plist))
  (setq mylist (json-read-from-string "[{\"name\": \"Adam\", \"id\": \"1\"},
                                        {\"name\": \"Eve\", \"id\": \"2\"}]")))

I want to find out Adam's id. How do I do that?

I'm currently trying

(dolist (person  mylist)
  (when (equal "Adam" (plist-get person :name))
    (setq person_id (plist-get person :id)))
  )

But this raises setq: Wrong type argument: listp, [(:id "1" :name "Adam") (:id "2" :name "Eve")]

andreas-h
  • 1,559
  • 13
  • 22

2 Answers2

6

You can instruct json-read-from-string to parse JSON arrays as elisp lists by let binding json-array-type to list like so

(let ((json-object-type 'plist)
      (json-array-type 'list))
  (setq mylist (json-read-from-string "[{\"name\": \"Adam\", \"id\": \"1\"},
                                        {\"name\": \"Eve\", \"id\": \"2\"}]")))                                 {\"name\": \"Eve\", \"id\": \"2\"}]")))

mylist now would be an elisp list which you manipulate/traverse using existing list functions.

andreas-h
  • 1,559
  • 13
  • 22
Iqbal Ansari
  • 7,468
  • 1
  • 28
  • 31
0

Working with vectors is a tad bothersome as only the most basic operations have been implemented. Here's a handcoded loop:

(let* ((json-object-type 'plist)
       (vector (json-read-from-string "[{\"name\": \"Adam\", \"id\": \"1\"},
                                        {\"name\": \"Eve\", \"id\": \"2\"}]"))
       (i 0)
       value)
  (while (and (< i (length vector)) (not value))
    (let ((person (aref vector i)))
      (when (string= (plist-get person :name) "Adam")
        (setq value (plist-get person :id))))
    (setq i (1+ i)))
  value)
wasamasa
  • 21,803
  • 1
  • 65
  • 97