我的项目使用一个读/写库解析JSON,该库名为:
我遇到了一些问题,试图让解码(func)工作,所以我开始胡乱操作:
我的JSON包含由名为"zone“的字段组成的数据,该字段包含一个内部带有:键的向量,例如{:zone::hand :table},该数据存储在向量中的字符串中,存储方式如下:{"zone”:"hand“"table"}
因此,我想出了如何使用以下命令转换示例数据:
(mapv keyword {"zone" : ["hand"]})这很棒,然后我需要弄清楚如何为柴郡实现一个解码器,我不能用我的逻辑做到这一点,我只花了大约一个小时来做这件事,但我一直在使用data.json,我认为解码器功能相对简单。
我让我的项目工作起来了,下面是一些示例代码:
(ns clojure-noob.core (:require
[cheshire.core :refer [decode]]
[clojure.data.json :as j-data]
) (:gen-class))
(defn -main
"I don't do a whole lot ... yet."
[& args]
)这是在使用柴郡:
(let [init (decode "{\"zone\" : [\"hand\"]}" true
(fn [field-name]
(if (= field-name "zone")
(mapv keyword [])
[])))]
(println (str init)))这是使用data.json:
(defn my-value-reader [key value]
(if (= key :zone)
(mapv keyword value)
value))
(let [init (j-data/read-str
"{\"zone\" : [\"hand\"]}"
:value-fn my-value-reader
:key-fn keyword)]
(println (str init)))我想从控制台中得到这两个结果的最下面的结果:
{:zone ["hand"]}
{:zone [:hand]}问题是我想用柴郡p.s.我在读柴郡的工厂部分?也许这样更简单?
发布于 2018-09-11 16:29:21
我同意@TaylorWood的观点。别弄乱解码器,一次咬一口就行了。首先,解析json。第二,对结果进行转换。
(def data "{\"zone\" : [\"hand\"]}")
(-> data
(cheshire.core/decode true)
(update-in ["zone"] (partial mapv keyword)))
#=> {:zone [:hand]}发布于 2018-09-13 14:27:43
我建议您使用像schema.tools这样的工具来强制输入。您可以添加第二次传递,试图将JSON字符串强制转换为更丰富的clojure类型。
下面是一些示例代码!
;; require all the dependencies. See links below for libraries you need to add
(require '[cheshire.core :as json])
(require '[schema.core :as s])
(require '[schema.coerce :as sc])
(require '[schema-tools.core :as st])
;; your data (as before)
(def data "{\"zone\" : [\"hand\"]}")
;; a schema that wants an array of keywords
(s/defschema MyData {:zone [s/Keyword]})
;; use `select-schema` along with a JSON coercion matcher
(-> data
(json/decode true)
(st/select-schema MyData sc/json-coercion-matcher))
;; output: {:zone [:hand]}使用defschema定义所需的数据形状为您提供了序列化到JSON的通用解决方案,同时充分利用了Clojure的值类型。您的模式描述了预期的结果,而不是显式地“做”转换工作,并且希望强制可以做正确的事情!
库链接:- https://github.com/plumatic/schema - https://github.com/metosin/schema-tools#coercion
注意:您可以使用metosin/spec-tools对clojure.spec执行类似的操作。请查看他们的自述文件以获得一些帮助。
https://stackoverflow.com/questions/52266657
复制相似问题