使用circe预处理点符号样式字段

时间:2017-05-18 20:44:15

标签: json scala circe

我有一些json,其中包含一些像{"foo.bar" : "bash"}一样被扁平化为bson-ish格式的字段。我想将其转换为以下表示{"foo" : { "bar" : "bash"}},并想知道我在哪里进行这样的操作。使问题复杂化的是,可能存在需要正确合并的多个这样的字段,例如, {"foo.bar" : "a", "foo.bash" : "b", "foo.baz" : "c"} - > {"foo" : { "bar" : "a", "bash" : "b", "baz" : "c"}}

1 个答案:

答案 0 :(得分:7)

这是一个快速实施:

import io.circe.Json

val Dotted = "([^\\.]*)\\.(.*)".r

def expandDotted(j: Json): Json = j.arrayOrObject(
  j,
  js => Json.fromValues(js.map(expandDotted)),
  _.toList.map {
    case (Dotted(k, rest), v) => Json.obj(k -> expandDotted(Json.obj(rest -> v)))
    case (k, v) => Json.obj(k -> expandDotted(v))
  }.reduceOption(_.deepMerge(_)).getOrElse(Json.obj())
)

我没有真正使用或测试过它,但似乎有效:

scala> import io.circe.literal._
import io.circe.literal._

scala> val j1 = json"""{"foo.bar" : "a", "foo.bash" : "b", "foo.baz" : "c"}"""
j1: io.circe.Json =
{
  "foo.bar" : "a",
  "foo.bash" : "b",
  "foo.baz" : "c"
}

scala> expandDotted(j1)
res1: io.circe.Json =
{
  "foo" : {
    "baz" : "c",
    "bash" : "b",
    "bar" : "a"
  }
}

更深的嵌套:

scala> expandDotted(json"""{ "x.y.z": true, "a.b": { "c": 1 } }""")
res2: io.circe.Json =
{
  "a" : {
    "b" : {
      "c" : 1
    }
  },
  "x" : {
    "y" : {
      "z" : true
    }
  }
}

并且只是为了确认它没有弄乱未发送的密钥:

scala> expandDotted(json"""{ "a.b": true, "x": 1 }""").noSpaces
res3: String = {"x":1,"a":{"b":true}}

请注意,对于“冲突”(导致JSON对象和非对象JSON值的路径,或多个非对象值),行为是Json#deepMerge的行为:

scala> expandDotted(json"""{ "a.b": true, "a": 1 }""").noSpaces
res4: String = {"a":1}

scala> expandDotted(json"""{ "a": 1, "a.b": true }""").noSpaces
res5: String = {"a":{"b":true}}

...这可能是你想要的,但你也可以在这些情况下失败,或者不扩展碰撞路径,或者做你能想到的其他任何事情。

相关问题