在 Emacs 中发出 JSON 请求

问题描述 投票:0回答:3

我正处于编写 Emacs 主要模式 的早期阶段,用于浏览 Stack Exchange 网络上的站点并为网站做出贡献,与

dired
list-packages
的工作方式大致相同,并从
magit
获得了一些灵感和
org-mode

问题是,当然,我不知道首先如何将 Emacs 与 SE API (v2.1) 连接起来。我从未在 Elisp 中做过任何涉及网络连接的事情,尽管我对这门语言本身很满意(并且已经多次查看了package.el

)。

我从未使用过 JSON,尽管我正在学习

W3C 的教程

一个简单的“hello world”就足够了,可能类似于

(execute-json-query "/info")

W3C 教程似乎也没有讨论请求。我必须对此进行自己的研究。

我真的不知道自己在做什么;我昨天下午才开始狂热地工作。

json emacs elisp stackexchange-api
3个回答
27
投票
其他答案的问题是

Stack Exchange API 是 GZIP 的并且 Emacs 附带的 url.el 不会自动解压缩它。

看一下我的

request.el库,它支持自动解压(说实话,我只是添加了支持)。下面是一个获取 stackoverflow 中最活跃问题的示例:

(request "https://api.stackexchange.com/2.1/questions" :params '((order . "desc") (sort . "activity") (site . "stackoverflow")) :parser 'json-read :success (function* (lambda (&key data &allow-other-keys) (let* ((item (elt (assoc-default 'items data) 0)) (title (assoc-default 'title item)) (tags (assoc-default 'tags item))) (message "%s %S" title tags)))))
request.el 

有详细记录,附带可执行示例并且经过良好测试


11
投票

8
投票
这可能不是最好的做事方式,但它似乎对我有用。

(defun fetch-json (url) (with-current-buffer (url-retrieve-synchronously url) ; there's probably a better way of stripping the headers (search-forward "\n\n") (delete-region (point-min) (point)) (buffer-string)))

然后使用 url 调用此函数将返回响应的内容,在本例中为 json。我使用 reddit api 作为示例,因为我不确定 Stack Exchange api 是如何工作的。

(fetch-json "http://reddit.com/r/emacs.json")

这里几乎没有错误检查,如果 url 没有返回数据,那么这将会崩溃。

© www.soinside.com 2019 - 2024. All rights reserved.