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

Abe*_*son 7 json scala circe

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

Tra*_*own 8

这是一个快速实现:

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())
)
Run Code Online (Sandbox Code Playgroud)

我没有真正使用或测试它的细节,但似乎工作:

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"
  }
}
Run Code Online (Sandbox Code Playgroud)

并且有更深的嵌套:

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

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

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

请注意,在"冲突"(导致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}}
Run Code Online (Sandbox Code Playgroud)

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