読者です 読者をやめる 読者になる 読者になる

Let's write β

趣味で書いたこととか、RustとLispが好き

CommonLispではてなブックマークAPI

Lisp

ちょっと情報を抽出したい事があったので、片手間ですが、つくってみました。

(ql:quickload :drakma)
(ql:quickload :cl-json)

(setq drakma:*text-content-types* 
      (cons '("application" . "json") 
            drakma:*text-content-types*))
(setq drakma:*header-stream* nil)

(defun get-hatebu-info (url)
  (json:decode-json-from-string
    (drakma:http-request 
      (format nil "http://b.hatena.ne.jp/entry/json/~A"
              url))))

(defclass <bookmark-entry> ()
  ((title :initarg :title :accessor title)
   (url :initarg :url :accessor url)
   (entry-url :initarg :entry-url :accessor entry-url)
   (screenshot :initarg :screenshot :accessor screenshot)
   (eid :initarg :eid :accessor eid)
   (related :initarg :related :accessor related)
   (bookmarks :initarg :bookmarks :accessor bookmarks)))

(defclass <user-bookmark> ()
  ((timestamp :initarg :timestamp :accessor timestamp)
   (user :initarg :user :accessor user)
   (tags :initarg :tags :accessor tags)
   (comment   :initarg :comment   :accessor comment)))

(defun parse-book-mark-info (info)
  (let ((bookmarks (cdr (assoc :bookmarks info)))
        (related (cdr (assoc :related info))))
    (make-instance '<bookmark-entry>
                   :title (cdr (assoc :title info))
                   :url (cdr (assoc :url info))
                   :entry-url (cdr (assoc :entry--url info))
                   :eid (cdr (assoc :eid info))
                   :screenshot (cdr (assoc :screenshot info))
                   :bookmarks
                   (loop for bk in bookmarks
                         collect (make-instance '<user-bookmark>
                                                :timestamp (cdr (assoc :timestamp bk))
                                                :tags (cdr (assoc :tags bk))
                                                :user (cdr (assoc :user bk))
                                                :comment   (cdr (assoc :comment bk))))
                   :related
                   (loop for rt in related 
                         collect (make-instance '<bookmark-entry>
                                                :title (cdr (assoc :title rt))
                                                :url (cdr (assoc :url rt))
                                                :entry-url (cdr (assoc :entry--url rt))
                                                :eid (cdr (assoc :eid rt)))))))

(defun get-hatebu (url)
  (parse-book-mark-info (get-hatebu-info url)))

こんな感じで情報がひっぱれてます。

(comment (car (bookmarks (get-hatebu "http://common-lisp.net/project/cl-json/"))))
=>"lispのリスト構造をJSONで表現"

僕が働いているAzit.incでは一緒に働けるエンジニアを募集しています!
採用情報 — 株式会社アジット|Azit Inc.