LoginSignup
0
0

More than 5 years have passed since last update.

YASONでのJSONオブジェクトのキーの扱い

Posted at

YASONでは基本的にJSONオブジェクトのキーを文字列で表現しますが、

(yason:parse "{\"x\":0}" :object-as :alist)
;=> (("x" . 0))

キーワードシンボルやシンボルで表現したい場合、動作をカスタマイズすることができます。

;; キーワード引数で動作を変更
(yason:parse "{\"x\":0}"
             :object-as :alist
             :object-key-fn (lambda (x) (intern x :keyword)))
;=> ((:\x . 0))

;; スペシャル変数で動作を変更
(let ((yason:*parse-object-key-fn* (lambda (x) (intern x :keyword))))
  (yason:parse "{\"x\":0}" :object-as :alist))
;=> ((:\x . 0))

JSONオブジェクトのキーは大文字と小文字を区別するため、名前に小文字を含むシンボルが作られることがあることに注意してください。

encode-alistやencode-plistはシンボルのキーと文字列のキーの両方を扱えます。(YASON 0.5.2以前ではシンボルのキーしか扱えませんので気を付けてください)

(yason:encode-alist '(("x" . 0)))
(yason:encode-alist '((|x| . 0)))
(yason:encode-alist '((:|x| . 0)))
;-> {"x":0}

encodeでオブジェクトをエンコードする場合、シンボルをエンコードするためのメソッドを定義します。

(defmethod yason:encode ((object symbol) &optional (stream *standard-output*))
  (yason:encode (symbol-name object) stream))

(let ((ht (make-hash-table :test #'equal)))
  (setf (gethash :|x| ht) 0)
  (yason:encode ht))
;-> {"x":0}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0