从data.json转换为柴郡

时间:2019-05-22 15:57:32

标签: clojure 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)))

功能键读取器功能:

(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->消息msg)

msg是一个json字符串。

但是我在尝试以下操作时出现以下错误:

  

tech.matterindustries.titan.ion.lambda.sqs-receive / json-> messages(sqs_receive.clj:36)上的执行错误(ArityException)。   错误的args(5)个传递给:cheshire.core / parse-smile

1 个答案:

答案 0 :(得分:0)

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

还请保持代码的清洁和格式化,如下所示:

(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看上去 与柴郡/读字符串所期望的不符