下面显示了如何将数据读/写到 JSON 字符串或 EDN 字符串中。
请注意,JSON 和 EDN 都是字符串序列化格式,尽管 Clojure 文字数据结构通常(草率地)称为“EDN 数据”,即使 EDN 在技术上意味着字符串表示。
另外,请注意clojure.tools.reader.edn是将 EDN 字符串转换为 Clojure 数据结构的最佳(最安全)方法。
(ns tst.demo.core
(:use tupelo.core tupelo.test)
(:require
[clojure.tools.reader.edn :as edn]
[tupelo.core :as t]
[tupelo.string :as ts] ))
(def data
"A clojure data literal"
{:a "hello" :b {:c [1 2 3]}})
(dotest
(let [json-str (t/edn->json data) ; shortcut to Cheshire
from-json (t/json->edn json-str) ; shortcut to Cheshire
edn-str (pr-str data) ; convert Clojure data structure => EDN string
; Using clojure.tools.reader.edn is the newest & safest way to
; read in an EDN string => data structure
from-edn (edn/read-string edn-str)]
; Convert all double-quotes to single-quotes for ease of comparison
; with string literal (no escapes needed)
(is= (ts/quotes->single json-str) "{'a':'hello','b':{'c':[1,2,3]}}")
(is= (ts/quotes->single edn-str) "{:a 'hello', :b {:c [1 2 3]}}")
; If we don't convert to single quotes, we get a messier escaped
; string literals with escape chars '\'
(is-nonblank= json-str "{\"a\":\"hello\",\"b\":{\"c\":[1,2,3]}}")
(is-nonblank= edn-str "{:a \"hello\", :b {:c [1 2 3]}}")
; Converting either EDN or JSON string into clojure data yields the same result
(is= data
from-json
from-edn)))