json - 将 circe 中 json 对象的所有键从 `underscore` 转换为 `camel case`

标签 json scala circe

起源

{
  "first_name" : "foo",
  "last_name" : "bar",
  "parent" : {
    "first_name" : "baz",
    "last_name" : "bazz",
  }
}

预期的
 {
      "firstName" : "foo",
      "lastName" : "bar",
      "parent" : {
        "firstName" : "baz",
        "lastName" : "bazz",
      }
    }

如何转换 json 对象的所有键?

最佳答案

这就是我写这个的方式。它没有我想要的那么简洁,但并不可怕:

import cats.free.Trampoline
import cats.std.list._
import cats.syntax.traverse._
import io.circe.{ Json, JsonObject }

/**
 * Helper method that transforms a single layer.
 */
def transformObjectKeys(obj: JsonObject, f: String => String): JsonObject =
  JsonObject.fromIterable(
    obj.toList.map {
      case (k, v) => f(k) -> v
    }
  )

def transformKeys(json: Json, f: String => String): Trampoline[Json] =
  json.arrayOrObject(
    Trampoline.done(json),
    _.traverse(j => Trampoline.suspend(transformKeys(j, f))).map(Json.fromValues),
    transformObjectKeys(_, f).traverse(obj => Trampoline.suspend(transformKeys(obj, f))).map(Json.fromJsonObject)
  )

进而:
import io.circe.literal._

val doc = json"""
{
  "first_name" : "foo",
  "last_name" : "bar",
  "parent" : {
    "first_name" : "baz",
    "last_name" : "bazz"
  }
}
"""

def sc2cc(in: String) = "_([a-z\\d])".r.replaceAllIn(in, _.group(1).toUpperCase)

最后:
scala> import cats.std.function._
import cats.std.function._

scala> transformKeys(doc, sc2cc).run
res0: io.circe.Json =
{
  "firstName" : "foo",
  "lastName" : "bar",
  "parent" : {
    "firstName" : "baz",
    "lastName" : "bazz"
  }
}

我们可能应该有一些递归应用 Json => F[Json] 的方法。这样转换更方便。

关于json - 将 circe 中 json 对象的所有键从 `underscore` 转换为 `camel case`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37583877/

相关文章:

java - 从响应实体 json 获取一个字段

json - 预期解码 Dictionary<String, Any> 但发现了一个数字

scala - 按需 Actor 获取或创建

json - 斯卡拉和瑟茜 : JSON encoding with optional fields

json - 在 Coldfusion 中的 api Web 服务中以 json 格式发送纯文本

json - 从golang中的json数组中删除特定元素

scala - 问题让 SBT 在 Mac OS X 上工作

scala - Scala 中是否有可能保证尾递归优化?

json - 在 Circe 中解析原始类型

scala - 使用 Http4s 的 Circe 编码器和解码器