从 data.json 转换为柴郡

Convert from data.json to cheshire

我对 Clojure 完全陌生。有时我仍然难以阅读函数。

我正在尝试更改此功能以使用 checkshire。 这是我的尝试:

defn- json->messages [json]
(let [records          (:amazon.aws.sqs/records (cheshire/decode
                                                json
                                                :key-fn key-reader
                                                :value-fn value-reader))
    add-origin-queue (fn [record]
                       (let [event-source-arn (:amazon.aws.sqs/event-source-arn record)
                             queue-name       (arn->queue-name event-source-arn)]
                         (assoc record :amazon.aws.sqs/queue-name queue-name)))]
(map add-origin-queue records)))

功能键-reader功能:

(def ^:private
key-reader
(memoize (fn [key]
         (let [kebab-key (if (= "md5OfBody" key)
                           "md5-of-body"
                           (csk/->kebab-case key))]
           (keyword "amazon.aws.sqs" kebab-key)))))

函数:

(def ^:private
value-reader
(memoize (fn [key value]
         (if (= key :amazon.aws.sqs/receipt-handle)
           value-reader
           value))))

我会像这样调用函数:

(json->messages msg)

msg 是一个 json 字符串。

但是我在尝试时遇到以下错误:

Execution error (ArityException) at tech.matterindustries.titan.ion.lambda.sqs-receive/json->messages (sqs_receive.clj:36). Wrong number of args (5) passed to: cheshire.core/parse-smile

您向 cheshire.core/parse-smile 发送了错误数量的参数。你有样本数据吗?

还请保持您的代码整洁并格式化,如下所示:

(defn- json->messages
  [json]
  (let [records          (:amazon.aws.sqs/records (cheshire/decode json :key-fn key-reader :value-fn value-reader))
        add-origin-queue (fn [record]
                           (let [event-source-arn (:amazon.aws.sqs/event-source-arn record)
                                 queue-name       (arn->queue-name event-source-arn)]
                             (assoc record :amazon.aws.sqs/queue-name queue-name)))]
    (map add-origin-queue records)))

我在 Cheshire 文档中找不到 decode,但在源代码中有这样的内容:

(def decode "Alias to parse-string for clojure-json users" parse-string)

我对他们不完整的文档感到失望。

快速 google 显示文档:

(parse-string string & [key-fn array-coerce-fn])

Returns the Clojure object corresponding to the given JSON-encoded string.
An optional key-fn argument can be either true (to coerce keys to keywords),
false to leave them as strings, or a function to provide custom coercion.

The array-coerce-fn is an optional function taking the name of an array field,
and returning the collection to be used for array values.

这个可能不清楚。这意味着有 3 种合法的方式调用 parse-string:

(parse-string  <json-str>)
(parse-string  <json-str>  <key-fn>)
(parse-string  <json-str>  <key-fn>  <array-coerce-fn>)

因此您可以使用 1、2 或 3 个参数调用它。您不能像示例中那样添加 :key-fn:value-fn 映射键。

另请注意,您的 key-readervalue-reader 看起来 与 cheshire/read-string 的预期不符 .