elisp怎么取值?

我在~目录下有个proxy.json文件,文件内容:

{
		"http":"username:passwd@proxyhkcom:8080",
		"https" :"username:passwd@proxyhkcom:8080",
		"enable": "false"
}   

我用json-read-file读取这个文件里面的值.

(json-read-file "~/proxy.json")

这个函数可以获取结果

((http . "username:passwd@proxyhkcom:8080") (https . "username:passwd@proxyhkcom:8080") (enable . "false"))

请问我怎么把http 和https这两个值取出来? elisp全小白。大佬们给个比较全的代码看看。 我想要个函数能从json文件里面去读取配置。

;; -*- lexical-binding: t -*-
;; example of `alist-get'
(alist-get 'http
           '((http . “username:passwd@proxyhkcom:8080”)
             (https . “username:passwd@proxyhkcom:8080”)
             (enable . “false”)))

;; body

;; 用了闭包,不過如果你有 JS 基础的话应該不会有理解困難。
(let (tmp)
  (defun read-file (path)
    (setq tmp (json-read-file path)))
  (defun get-key-val (key)
    (alist-get key tmp)))

;; test
(read-file "~/proxy.json")
;; ((http . "username:passwd@proxyhkcom:8080") (https . "username:passwd@proxyhkcom:8080") (enable . "false"))

(get-key-val 'https)
;; "username:passwd@proxyhkcom:8080"

(get-key-val 'https)

;; “username:passwd@proxyhkcom:8080”

这种求值后的结果,自动注释起来,怎么做到的,用什么 mode 吗?

(read-json-file (expand-file-name “configuration/proxy.json” user-emacs-directory))

(if (equal (get-key-val 'enable) 1)

(setq url-proxy-services
'(("no_proxy" . "^\\(localhost\\|10.*\\)")
        ("http" . (get-key-val 'http))
        ("https" . (get-key-val 'https))))

(message “%S” “proxy-disable”) )

大佬,你这个厉害。 我还有个问题。 上面那个函数执行了之后,url-proxy-services的值为什么是

((“no_proxy” . “^\(localhost\|10.*\)”) (“http” get-key-val (quote http)) (“https” get-key-val (quote https)))

因为求值的时候,用了 'quote ,导致不会对整个list求值。可以改用 backquote ,它与 quote 不同之处在于可以用逗号 , 对需要的结果求值:

(setq url-proxy-services
`(("no_proxy" . "^\\(localhost\\|10.*\\)")
        ("http" . ,(get-key-val 'http))
        ("https" . ,(get-key-val 'https))))

這两个实际是一樣的,只是 print 出來以后不一樣,你可以理解为 'http(quote http) 的语法糖,'(x . (y z))(x y z) 的糖。

而且你的用法不对,按你的实际意思,应該用

(setq url-proxy-services
`(("no_proxy" . "^\\(localhost\\|10.*\\)")
        ("http" . ,(get-key-val 'http))
        ("https" . ,(get-key-val 'https))))

你还是要先看个入门啥的。

https://emacs-china.org/search?q=Emacs%20Lisp%20%E7%AE%80%E6%98%8E%E6%95%99%E7%A8%8B

见笑了,都是手打的。


要自动也不难;

(defun eval-print-last-sexp* (&optional eval-last-sexp-arg-internal)
  (interactive "P")
  (let ((standard-output (current-buffer)))
    (terpri)
    (princ ";; ")
    (eval-last-sexp (or eval-last-sexp-arg-internal t))
    (terpri)))
eval-print-last-sexp*

(define-key lisp-interaction-mode-map (kbd "C-j") 'eval-print-last-sexp*)

(list 1 2)
;; (1 2)
1 个赞

厉害! 下面这个是我谷歌的,还是你那个函数比较容易看懂

(defun read-proxy-configuration()
  (let ((json-object-type 'plist)
	(json-array-type 'list))
    (setq mylist (json-read-file (expand-file-name "configuration/proxy.json" user-emacs-directory))))
  (setq proxy-http (plist-get mylist :http))
  (setq proxy-https (plist-get mylist :https))
  (setq proxy-enable (plist-get mylist :enable)))

:slight_smile: nice 因为我在多次地方看到过类似的效果,以为有现成的