I want to read config.json file inside .emacs, how can I do this?
(require 'json)
(setq config (json-read-from-string (read-file "config.json")))
You can simplify your code to:
(defun my-file-contents (filename)
"Return the contents of FILENAME."
(with-temp-buffer
(insert-file-contents filename)
(buffer-string)))
edit: Although in this particular instance, I see that json-read-file
is already defined, which cuts out the middle man.
Emacs 24.5 defines it like so:
(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)))
For JSON just use json-read-file
. For general files f
library provides f-read-bytes
and f-read-text
:
(f-read-text "file.txt" 'utf-8)
I ended up with this code:
(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))))
For those you dislike writing quite so much code you can use f-read
from the f
library (not part of the standard library). This comes from this question: elisp: read file into list of lists
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With