7

JSON:

{
  "name": "xxxxx",
  "job": "xxxxxx",
  "projects": [
    {
      "name": "xxxxx",
      "date": "xxxxx",
      "about": "xxxxxxxxxx"
    },
    {
      "name": "xxxxx",
      "date": "xxxxx",
      "about": "xxxxxxxxxx"
    },
    {
      "name": "xxxxx",
      "date": "xxxxx",
      "about": "xxxxxxxxxx"
    }
  ]
}

Elisp file:

(let ((json-object-type 'hash-table)
      (json-array-type 'list)
      (json-key-type 'string))
  (setq data (with-temp-buffer
               (insert-file-contents (elt argv 0))
               (buffer-string))))

How to access the first element in projects list (json array)?

Note: According to https://github.com/thorstadt/json.el/blob/master/json.el (read-json) should be used instead of setq but it doesn't show a clear example on how to do that. Also I have chosen hash-tables as the json-object-type as in comparision of plist and alist it seems favorable to me.

2
  • Only one question per question, please.
    – Drew
    Commented Sep 28, 2016 at 6:13
  • @Drew burden my curiosity, I thought it is such a common operation, that a good answer would suffice for all the questions included.
    – I'm Mo
    Commented Sep 28, 2016 at 6:20

1 Answer 1

13

I've taken the liberty of adjusting your code appropriately:

(require 'json)

(let* ((json-object-type 'hash-table)
       (json-array-type 'list)
       (json-key-type 'string)
       (json (json-read-file "test.json")))
  (car (gethash "projects" json)))

The let* is required because otherwise the call to json-read-file will not see the previously bound values as let sets them in parallel...

As for the access functions, gethash retrieves a value by key from a hash table, whereas car returns the first list element. If you need a different one, you can use nth with an index.

To actually iterate over the projects:

(require 'json)

(let* ((json-object-type 'hash-table)
       (json-array-type 'list)
       (json-key-type 'string)
       (json (json-read-file "test.json"))
       (projects (gethash "projects" json)))
  (dolist (project projects)
    ...))
2
  • thank you for your answer. how can i get access to the resulting list from (car (gethash "projects" json))) to use it in a dolist(project projects) ?
    – I'm Mo
    Commented Sep 28, 2016 at 6:45
  • This does not result into a list, but a hash table. Assuming you actually want to iterate over all projects, don't access the first list item in the first place.
    – wasamasa
    Commented Sep 28, 2016 at 7:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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