簡體   English   中英

Clojure:在動態嵌套map / seq中搜索/替換值

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM