1

我的项目使用读/写库解析 JSON,称为:

柴郡核心

我遇到了问题,试图让解码(func)工作,所以我开始搞乱:

数据.json

我的 JSON 包含由名为“zone”的字段组成的数据,其中包含一个带有 :keys 的向量,例如 {:zone : [:hand :table]} 存储在向量中的字符串中,如下所示:{“zone " : ["手" "桌子"]}

所以我想出了如何使用以下方法转换示例数据:

(mapv keyword {"zone" : ["hand"]})

太好了,然后我需要弄清楚如何为 cheshire 实现解码器,我的逻辑无法做到这一点,我只花了大约一个小时的时间,但我一直在使用 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]}

问题是我想使用 cheshire ps 我正在阅读 cheshire 的工厂部分吗?也许这更容易?

4

2 回答 2

0

我同意@TaylorWood。不要乱用解码器,一次咬一口。首先,解析json。第二,转换结果。

(def data "{\"zone\" : [\"hand\"]}")

(-> data 
    (cheshire.core/decode true)
    (update-in ["zone"] (partial mapv keyword)))
#=> {:zone [:hand]}
于 2018-09-11T08:29:20.503 回答
0

我建议您使用诸如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 做类似的事情。查看他们的自述文件以获得一些帮助。

于 2018-09-13T06:27:43.047 回答