我想在.emacs文件中读取config.json文件,应该怎么做?
(require 'json)
(setq config (json-read-from-string (read-file "config.json")))
您可以将代码简化为:
(defun my-file-contents (filename)
"Return the contents of FILENAME."
(with-temp-buffer
(insert-file-contents filename)
(buffer-string)))
编辑:虽然在这个特定的例子中,我发现json-read-file
已经被定义了,这就省去了中间人。
Emacs 24.5的定义如下:
(defun json-read-file (file)
"Read the first JSON object contained in FILE and return it."
(with-temp-buffer
(insert-file-contents file)
(goto-char (point-min))
(json-read)))
对于 JSON 文件,只需使用 json-read-file
。对于其他文件,f
库提供了 f-read-bytes
和 f-read-text
:
(f-read-text "file.txt" 'utf-8)
(defun read-file (filename)
(save-excursion
(let ((new (get-buffer-create filename)) (current (current-buffer)))
(switch-to-buffer new)
(insert-file-contents filename)
(mark-whole-buffer)
(let ((contents (buffer-substring (mark) (point))))
(kill-buffer new)
(switch-to-buffer current)
contents))))