【问题标题】:JSONPath and json4sJSONPath 和 json4s
【发布时间】:2017-07-21 14:22:40
【问题描述】:

我需要从消息中提取一个字段值:

{
  "data": {
    "code": "404",
    ...
  }
}

JSONPath 表达式存储在一个变量中:

val path = "/data/code"

我正在使用json4s 来处理 JSON。

从文档中,可以使用 DSL 实现这一点:

val json = parse(message)
val code = json \ "data" \ "code"

它可以工作,但显然 JSONPath 表达式应该是硬编码的。 有没有办法评估存储为字符串的表达式? 比如:

val code = json.evaluateJSONPath(path)

【问题讨论】:

    标签: json scala jsonpath json4s


    【解决方案1】:

    假设 json 路径以逗号分隔的字符串格式提供,则以下内容将起作用。

    import org.json4s._
    import org.json4s.native.JsonMethods._
    val json = parse(""" { "data": { "code": "404", "foo": "bar" } } """)
    val path = "data,code" // json path in string 
    path.split(',').foldLeft(json)({ case (acc, node) => acc \ node })
    

    编辑: 添加隐式类以简化访问

    implicit class JsonHelper(json: JValue) {
        def customExtract[T](path: String)(implicit formats: Formats, mf: Manifest[T]) = {
            path.split(',').foldLeft(json)({ case (acc: JValue, node: String) => acc \ node }).extract[T]
        }
    }
    
    json.customExtract[String]("data,code")
    res23: String = "404"
    

    【讨论】:

    • 谢谢。但我希望能提出更简洁的建议。
    • 当然。我已经用一个隐式类更新了答案以简化访问。
    【解决方案2】:

    如何使用高阶函数来映射提取命令,比如:

    val extractCodeFunc = (j: JValue) => j \ "data" \ "code"
    

    并提取json:

    val res = extractCodeFunc.apply(json)
    

    【讨论】:

    • 我更喜欢避免硬编码路径。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-09
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 2020-10-13
    相关资源
    最近更新 更多