2012-10-21 60 views
5

我使用json.el和furl.el從toggl.com的API獲取時間條目 - 不幸的是,我不認爲它將響應分離爲多個列表:Elisp - 從字符串讀取API的響應

JSON響應(在數據的兩個條目):

{"data":[{"id":50439783,"description":"bar","billable":false,"start":"2012-10-20T18:07:00Z","stop":"2012-10-20T22:39:00Z","duration":16320,"workspace":{"id":172049,"name":"Dan's workspace"},"tag_names":[],"ignore_start_and_stop":false,"updated_at":"2012-10-20T22:40:26Z","user_id":231062},{"id":50440682,"description":"Test Time Entry","billable":false,"start":"2012-10-20T23:40:16Z","stop":"2012-10-20T23:50:16Z","duration":600,"workspace":{"id":172049,"name":"Dan's workspace"},"tag_names":[],"ignore_start_and_stop":false,"updated_at":"2012-10-20T23:51:32Z","user_id":231062}],"related_data_updated_at":"2012-10-19T00:00:00Z"} 

JSON-讀從字符串響應:

(related_data_updated_at . 2012-10-19T00:00:00Z)                               
(data . [((user_id . 231062) (updated_at . 2012-10-20T22:40:26Z) (ignore_start_and_stop . :json-false) (tag_names . []) (workspace ... ...) (duration . 16320) (stop . 20\ 
12-10-20T22:39:00Z) (start . 2012-10-20T18:07:00Z) (billable . :json-false) (description . bar) (id . 50439783)) ((user_id . 231062) (updated_at . 2012-10-20T23:51:32Z) \ 
(ignore_start_and_stop . :json-false) (tag_names . []) (workspace ... ...) (duration . 600) (stop . 2012-10-20T23:50:16Z) (start . 2012-10-20T23:40:16Z) (billable . :jso\ 
n-false) (description . Test Time Entry) (id . 50440682))]) 

因此,如果考慮到列表中的多個條目,怎麼可能我訪問第一個?汽車顯示related_data_updated_at和關鍵數據。 cdr顯示related_data_updated_at的val,等等。

我不認爲elisp的幫助很多,但在這裏它只是櫃面:

(defun toggl-display-time-entries(json-string)                                
    (with-current-buffer (get-buffer-create "Toggl")                               
    (erase-buffer)                                       
    (let ((inhibit-read-only t)                                   
      (time-entries (json-read-from-string json-string)))                            
     (dolist (time-entry time-entries)                                 
     (newline)                                       
     (insert (format "%s" (cdr time-entry))))))) 

回答

4

你接近,但你需要提取「數據,然後迭代這個數組,而不是一個名單。例如,這將打印陣列中每個項目的用戶標識:

(let ((array-of-times 
     (cdr 
    (assoc 'data 
      (json-read-from-string json-string))))) 
    (let ((c (length array-of-times))) 
    (dotimes (n c) 
     (insert (format "user_id %s\n" (cdr (assoc 'user_id (elt array-of-times n))))))))