cl-defstruct 定义出来的不能使用 json-encode 吗

  1. record-to-list
(defun record-to-list (record)
  "Convert RECORD to list."
  (with-temp-buffer
    (prin1 record (current-buffer))
    (goto-char (point-min))
    (when (and (re-search-forward "#s" nil t) (= (char-after) ?\())
      (read (current-buffer)))))

(record-to-list (person-create :name "Tom" :age 20 :sex "Male"))
;; => (person "Tom" 20 "Male")
  1. struct-to-alist
(defun struct-to-alist (instance)
  "Convert struct to alist."
  (let ((lst (record-to-list instance)))
    (cl-loop for slot in (cdr (cl-struct-slot-info (car lst)))
             for value in (cdr lst)
             collect (cons (car slot) value))))

(struct-to-alist (person-create :name "Tom" :age 20 :sex "Male"))
;; => ((name . "Tom") (age . 20) (sex . "Male"))

EDIT: 去掉 struct-to-aliststruct-type 参数。

3 个赞