[英]Clojure: search/replace values in a dynamic nested map/seq
我有一个动态创建的地图数据结构,稍后将被解析为JSON。 因此,嵌套级别等是未知的并且取决于数据。
如果键具有多个值,则它们在序列内表示为映射。
这是一个例子:
{:key "value"
:anotherKey "anotherValue"
:foo "test"
:others [ {:foo "test2"} {:foo "test3"} ]
:deeper {:nesting {:foo "test4"} }
}
我现在想要搜索密钥:foo
并将"/bar"
附加到值。
结果应该返回修改后的地图:
{:key "value"
:anotherKey "anotherValue"
:foo "test/bar"
:others [ {:foo "test2/bar"} {:foo "test3/bar"} ]
:deeper {:nesting {:foo "test4/bar"} }
}
实现这一目标的干净简单方法是什么?
我尝试了一种递归方法,但除了大数据结构的内存问题之外,我正在努力返回我的附加值。
可能有一些比这更简单的事情:
(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"}]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.