简体   繁体   English

clojure.data.json / write-str:指定用于将值放入聚合数组的键函数

[英]clojure.data.json/write-str: specifying a key function for placing values into aggregate arrays

Suppose I have a simple map, example-map : 假设我有一个简单的地图, example-map

(def example-map {"s" {"f" "g"} 
                  "m" {"r" "q"}}) 

I can use clojure.data.json/write-str to JSON-ify this map as such: 我可以使用clojure.data.json/write-str来对地图进行JSON修饰,例如:

(clojure.data.json/write-str example-map) =>
"{\"s\":{\"f\":\"g\"},\"m\":{\"r\":\"q\"}}"

I'd like to conditionally place some of the values into lists according to the value of their keys. 我想根据其键的值有条件地将一些值放入列表中。

write-str provides an optional :key-fn , which applies some function to key value pairs. write-str提供了一个可选的:key-fn ,它将某些功能应用于键值对。 For example, the desired function might specify that all values associated with entries that match "s" are placed in lists. 例如,所需函数可以指定将与匹配"s"条目相关联的所有值都放在列表中。

(clojure.data.json/write-str example-map :key-function desired-function) =>
"{\"s\":[{\"f\":\"g\"}],\"m\":{\"r\":\"q\"}}"

Does anyone know how to specify such a key function that checks for membership of a key in a set and places the values associated with members into an array rendered in the output JSON? 有谁知道如何指定这样的键函数来检查集合中键的成员关系并将与成员相关联的值放入输出JSON中呈现的数组中?

Like your previous question, this is not a job for the JSON parser. 像您之前的问题一样,这不是JSON解析器的工作。 You don't need to rely on write-time features of your JSON library to adjust the shape of your JSON maps. 您无需依赖JSON库的写入时功能来调整JSON映射的形状。 Instead, you have a fully functional Turing complete language at your disposal: Clojure! 相反,您可以使用功能齐全的图灵完整语言:Clojure! If the maps don't already look the way you want them to be output, then write a function that takes one Clojure map as input and produces a different one as output; 如果这些地图看起来还不符合您希望的输出方式,请编写一个函数,该函数将一个Clojure地图作为输入,并生成另一个输出。 then ask your JSON library to write the output map, without any special rules for fiddling with the output. 然后让您的JSON库编写输出映射,而没有任何摆弄输出的特殊规则。

Now, as it happens this particular JSON library does provide an option named value-fn (not key-function as you claim) to let you modify a value in a map based on its key. 现在,碰巧的是,这个特定的JSON库确实提供了一个名为value-fn的选项(并非您声称的key-function ),可以让您根据其键在映射中修改值。 So you could use that, in which case you simply need to write a function with a signature like: 因此,您可以使用它,在这种情况下,您只需要编写带有签名的函数,例如:

(fn [k v]
  (...compute new value...))

There are many ways you could write such a function, but they are all entirely divorced from your JSON parser. 您可以通过多种方式编写此类函数,但它们完全与JSON解析器分离。 If you need help writing it, mention some specific things you need help with, so you can get a clear explanation for the part of the process that is actually giving you trouble. 如果需要编写帮助,请提及一些需要帮助的特定事项,这样您就可以清楚地了解过程中确实给您带来麻烦的那部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM