添加类似json的值
我有两个完全相似的JSON对象,我想添加相应键的值并返回一个JSON。JSON还将包含JSON数组。clojure的惯用做法是什么 输入JSON 1:添加类似json的值,json,clojure,Json,Clojure,我有两个完全相似的JSON对象,我想添加相应键的值并返回一个JSON。JSON还将包含JSON数组。clojure的惯用做法是什么 输入JSON 1: { "data":[ { "val1":{ "total":"1.00", "val2":{ "total":"1.00" }, "val3":{ "tot
{
"data":[
{
"val1":{
"total":"1.00",
"val2":{
"total":"1.00"
},
"val3":{
"total":"1.00"
}
}
}
]
}
{
"data":[
{
"val1":{
"total":"2.00",
"val2":{
"total":"3.00"
},
"val3":{
"total":"4.00"
}
}
}
]
}
{
"data":[
{
"val1":{
"total":"3.00",
"val2":{
"total":"4.00"
},
"val3":{
"total":"5.00"
}
}
}
]
}
输入JSON 2:
{
"data":[
{
"val1":{
"total":"1.00",
"val2":{
"total":"1.00"
},
"val3":{
"total":"1.00"
}
}
}
]
}
{
"data":[
{
"val1":{
"total":"2.00",
"val2":{
"total":"3.00"
},
"val3":{
"total":"4.00"
}
}
}
]
}
{
"data":[
{
"val1":{
"total":"3.00",
"val2":{
"total":"4.00"
},
"val3":{
"total":"5.00"
}
}
}
]
}
预期的JSON:
{
"data":[
{
"val1":{
"total":"1.00",
"val2":{
"total":"1.00"
},
"val3":{
"total":"1.00"
}
}
}
]
}
{
"data":[
{
"val1":{
"total":"2.00",
"val2":{
"total":"3.00"
},
"val3":{
"total":"4.00"
}
}
}
]
}
{
"data":[
{
"val1":{
"total":"3.00",
"val2":{
"total":"4.00"
},
"val3":{
"total":"5.00"
}
}
}
]
}
这可以通过3个步骤实现。我在下面的代码中提到了它们作为注释 Clojure字符串太强大了。 免责声明:这只适用于没有向量的数据结构
注意:请评论任何可能比传统方法更耗时的内容。首先,您需要解析json 将
[org.clojure/data.json“0.2.6”]
添加到您的:dependencies
向量中
(ns foo.bar
(:require
[clojure.data.json :as json]))
(defn read-input [path]
;; Substitute slurp for however you get the input.
(json/read-str (slurp path)
:key-fn keyword ; In clojure it's nice to have keys as keywords
:value-fn (fn [k v]
;; Parse the numbers.
(if (= :total k)
(Double/parseDouble v)
v))))
(def input1 (read-input "input1.json"))
(def input2 (read-input "input2.json"))
;; The parsed input.
(def input1 {:data [{:val1 {:total 5.0, :val2 {:total 4.0}, :val3 {:total 3.0}}}]})
(def input2 {:data [{:val1 {:total 1.0, :val2 {:total 1.0}, :val3 {:total 1.0}}}]})
然后要合并它们,可以使用nice核心函数merge with
和一些递归
(defn merge-jsons [a b]
(merge-with (fn [v1 v2]
(cond (every? vector? [v1 v2]) (mapv merge-jsons v1 v2)
(every? map? [v1 v2]) (merge-jsons v1 v2)
:else (+ v1 v2)))
a, b))
然后您只需要将其转换回json
(write str
有一个:value fn
选项,就像read str
一样,如果您确实需要这里的数字作为字符串)
您的json不正确。它有重复的键“val2”@minhtuannguyen抱歉,只是输入错误。请发布您为解决问题而编写的代码problem@mavbozo我们是clojure的新手,所以我们正在寻找clojure中的lib或惯用方式。