假设我们有2个json数组。 如何将它们合并为一个带有circe的单个数组? 例:
数组1:
[{"id": 1}, {"id": 2}, {"id": 3}]数组2:
[{"id": 4}, {"id": 5}, {"id": 6}]需要:
[{"id": 1}, {"id": 2}, {"id": 3}, {"id": 4}, {"id": 5}, {"id": 6}]我已经尝试过deepMerge ,但它只保留参数的内容,而不是调用对象的内容。
Let's say we have 2 json arrays. How to merge them into a single array with circe? Example:
Array 1:
[{"id": 1}, {"id": 2}, {"id": 3}]Array 2:
[{"id": 4}, {"id": 5}, {"id": 6}]Needed:
[{"id": 1}, {"id": 2}, {"id": 3}, {"id": 4}, {"id": 5}, {"id": 6}]I've tried deepMerge, but it only keeps the contents of the argument, not of the calling object.
最满意答案
假设我们有以下设置(为方便起见我使用circe-literal,但你的Json值可能来自任何地方):
import io.circe.Json, io.circe.literal._ val a1: Json = json"""[{"id": 1}, {"id": 2}, {"id": 3}]""" val a2: Json = json"""[{"id": 4}, {"id": 5}, {"id": 6}]"""现在我们可以像这样组合它们:
for { a1s <- a1.asArray; a2s <- a2.asArray } yield Json.fromValues(a1s ++ a2s)要么:
import cats.std.option._, cats.syntax.cartesian._ (a1.asArray |@| a2.asArray).map(_ ++ _).map(Json.fromValues)如果a1或a2不代表JSON数组,这两种方法都会给你一个Option[Json] ,它将是None 。 例如,由您来决定在这种情况下您想要发生什么.getOrElse(a2)或.getOrElse(a1.deepMerge(a2))可能是合理的选择。
作为附注, deepMerge的当前合同说明如下:
Null,Array,Boolean,String和Number被视为值,参数JSON中的值完全替换此JSON中的值。
但这并不是deepMerge ,将deepMerge连接到JSON数组可能并不合理 - 如果你想打开一个问题,我们可以多考虑一下。
Suppose we've got the following set-up (I'm using circe-literal for convenience, but your Json values could come from anywhere):
import io.circe.Json, io.circe.literal._ val a1: Json = json"""[{"id": 1}, {"id": 2}, {"id": 3}]""" val a2: Json = json"""[{"id": 4}, {"id": 5}, {"id": 6}]"""Now we can combine them like this:
for { a1s <- a1.asArray; a2s <- a2.asArray } yield Json.fromValues(a1s ++ a2s)Or:
import cats.std.option._, cats.syntax.cartesian._ (a1.asArray |@| a2.asArray).map(_ ++ _).map(Json.fromValues)Both of these approaches are going to give you an Option[Json] that will be None if either a1 or a2 don't represent JSON arrays. It's up to you to decide what you want to happen in that situation .getOrElse(a2) or .getOrElse(a1.deepMerge(a2)) might be reasonable choices, for example.
As a side note, the current contract of deepMerge says the following:
Null, Array, Boolean, String and Number are treated as values, and values from the argument JSON completely replace values from this JSON.
This isn't set in stone, though, and it might not be unreasonable to have deepMerge concatenate JSON arrays—if you want to open an issue we can do some more thinking about it.
更多推荐
发布评论