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.

Stefan
  • 26,154
  • 3
  • 46
  • 84
I'm Mo
  • 73
  • 1
  • 4

1 Answers1

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)
    ...))
wasamasa
  • 21,803
  • 1
  • 65
  • 97
  • 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 Sep 28 '16 at 06: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 Sep 28 '16 at 07:04