Search code examples
emacselisp

How to read contents of the file programmatically in Emacs?


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")))

Solution

  • 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)))