Clojure:在动态嵌套map/seq中搜索/替换值

ech*_*hox 2 collections clojure

我有一个动态创建的地图数据结构,稍后将被解析为JSON.因此,嵌套级别等是未知的并且取决于数据.

如果键具有多个值,则它们在序列内表示为映射.

这是一个例子:

{:key "value"
:anotherKey "anotherValue"
:foo "test"
:others [ {:foo "test2"} {:foo "test3"} ]
:deeper {:nesting {:foo "test4"} }
}
Run Code Online (Sandbox Code Playgroud)

我现在想要搜索密钥:foo并附"/bar"加到值.

结果应该返回修改后的地图:

{:key "value"
:anotherKey "anotherValue"
:foo "test/bar"
:others [ {:foo "test2/bar"} {:foo "test3/bar"} ]
:deeper {:nesting {:foo "test4/bar"} }
}
Run Code Online (Sandbox Code Playgroud)

实现这一目标的干净简单方法是什么?

我尝试了一种递归方法,但除了大数据结构的内存问题之外,我正在努力返回我的附加值.

sbe*_*nsu 10

可能有一些比这更简单的事情:

(clojure.walk/prewalk 
  (fn [m] 
    (if (and (map? m) (:foo m)) 
      (update-in m [:foo] #(str % "/bar")) 
      m)) 
  {:key "value"
   :anotherKey "anotherValue"
   :foo "test"
   :others [{:foo "test2"} {:foo "test3"}]
   :deeper {:nesting {:foo "test4"}}})

=>
{:anotherKey "anotherValue", 
 :key "value", 
 :deeper {:nesting {:foo "test4/bar"}}, 
 :foo "test/bar", 
 :others [{:foo "test2/bar"} {:foo "test3/bar"}]}
Run Code Online (Sandbox Code Playgroud)