【问题标题】:scala json4s how can i extract field by conditionscala json4s我如何按条件提取字段
【发布时间】:2016-07-15 09:28:19
【问题描述】:

我有json(例如):

{
  "name": "",
  "count": 2,
  "children": {
    "app_open": {
      "name": "app_open",
      "count": 1,
      "children": {
        "session_end": {
          "name": "session_end",
          "count": 1,
          "children": {}
        }
      }
    },
    "app_install": {
      "name": "app_install",
      "count": 2,
      "children": {
        "session_end": {
          "name": "session_end",
          "count": 2,
          "children": {}
        }
      }
    },
    "app_instal1l": {
      "name": "app_instal1l",
      "count": 3,
      "children": {
        "app_open": {
          "name": "app_open",
          "count": 3,
          "children": {
            "session_end": {
              "name": "session_end",
              "count": 3,
              "children": {}
            }
          }
        }
      }
    }
  }
}

我需要提取 "name" = "app_open" 的所有计数。

我尝试使用 json4s 库:

val name = jsonInput filterField {
           case JField("name", "app_open") => true
           case _ => false
         }
println("name = " + URL)

我建议在输出中我将只使用“app_open”,但我得到了:

name = List((name,JString(app_open)), (name,JString(session_end)), 
(name,JString(app_open)), (name,JString(session_end)))

我在这里做错了什么? 谢谢!

【问题讨论】:

    标签: json scala json4s


    【解决方案1】:

    编译器错误很明显:

    Error: type mismatch;
     found   : String("app_open")
     required: org.json4s.JsonAST.JValue
        case JField("name", "app_open") => true
                        ^
    

    那是因为type JField = (String, JValue)。像这样使用JValue 而不是String

    val name = jsonInput filterField {
      case JField("name", JString("app_open")) => true
      case _ => false
    }
    

    【讨论】:

    • 请注意,JField 是(String, JValue) 的类型别名,没有 JField 也可以匹配
    • 嗯,我在编译时没有错误,但您的解决方案正在运行)谢谢!
    猜你喜欢
    • 2016-10-14
    • 2015-02-17
    • 1970-01-01
    • 2017-05-19
    • 1970-01-01
    • 2020-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多