【问题标题】:Filter resulting JSON using circe使用 circe 过滤结果 JSON
【发布时间】:2021-04-02 18:14:42
【问题描述】:

我有一个已转换的 JSON 对象,我需要将其过滤到仅其原始键的子集。我已经查看了 circe 中 Json 对象的文档,但它似乎没有公开任何围绕过滤对象的 API。我必须为此使用光标吗?我考虑从案例类创建解码器,但是我的键中有一个特殊字符 .。下面是更多上下文代码/数据。

{
 "field.nested.this": "value",
 "field.nested.that": "value",
 "field.nested.where": "value"
}

创建不包含 field.nested.that 字段的新 JSON 实例的最佳方法是什么?

【问题讨论】:

    标签: scala circe


    【解决方案1】:

    我不确定这是否是您需要的:

    object Circe extends App {
      import io.circe._
      import io.circe.literal._
      import io.circe.syntax._
    
      //I'm using a json literal here.
      //If you have a runtime string from an external source
      // you would need to parse it with `io.circe.parser.parse` first
      val json: Json = json"""
        {
           "field.nested.this": "value",
           "field.nested.that": "value",
           "field.nested.where": "value"
        }
      """
    
      val maybeJsonFiltered =
        json.asObject.map(_.filterKeys(_ != "field.nested.that").asJson)
    
      println(maybeJsonFiltered)
      //  Some({
      //    "field.nested.this" : "value",
      //    "field.nested.where" : "value"
      //  })
    }
    

    或者,您也可以将其解析为地图 (json.as[Map[String, String]]) 或仅包含您需要的字段的自定义案例类,并将它们编码回 json。您可能需要为所有带有. 的字段添加@JsonKey 注释。

    【讨论】:

    猜你喜欢
    • 2019-10-20
    • 1970-01-01
    • 1970-01-01
    • 2016-04-01
    • 1970-01-01
    • 2012-08-23
    • 1970-01-01
    • 1970-01-01
    • 2014-10-23
    相关资源
    最近更新 更多