Skip to content

Instantly share code, notes, and snippets.

@bahmanm
Created June 15, 2023 20:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bahmanm/8f036451ca661f7f3f3f6588b6a4c15f to your computer and use it in GitHub Desktop.
Save bahmanm/8f036451ca661f7f3f3f6588b6a4c15f to your computer and use it in GitHub Desktop.
eLisp: Save and parse JSON
;; to save an object into a json file
(with-temp-buffer
(json-insert '(:foo "bar"))
(write-file "~/tmp/my.json"))
;; load a json file as hash table
(with-temp-buffer
(insert-file-contents "~/tmp/my.json")
(json-parse-buffer))
@rtrppl
Copy link

rtrppl commented Jun 16, 2023

Thanks. I haven't been working a lot with JSON before. Why does this not work (i.e. the output is "nil"):

;; to save an object into a json file
(with-temp-buffer
  (json-insert '(:foo "bar"))
  (json-insert '(:test "hallo"))
  (write-file "~/tmp/my.json"))
;; load a json file as hash table 
(with-temp-buffer
  (insert-file-contents "~/tmp/my.json")
  (if (fboundp 'json-parse-buffer)
    (setq my-json-data (json-parse-buffer)))
  (print (gethash "test" my-json-data)))

@bahmanm
Copy link
Author

bahmanm commented Jun 16, 2023

Each time you call json-insert a new JSON object is appended to the contents of the temp buffer. That is after the first section of your code the file looks like ⬇️ which is invalid json.

{"foo": "bar"}
{"test": "hallo"}

The idea is to call json-insert only once with the final configs object to be saved. For example:

(with-temp-buffer
  (let ((configs-to-be-saved '(:foo "bar")))
    (plist-put configs-to-be-saved
               :baz
               '(:x 10 :y "lorem"))
    (json-insert configs-to-be-saved)
    (write-file "~/tmp/my.json")))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment