如何从scala中的json中提取值

时间:2017-09-08 18:54:33

标签: json scala

我有json格式的弹性搜索SearchResponse,我想将值提取到scala中的float对象

response: org.elasticsearch.action.search.SearchResponse = {
  "took" : 3,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "failed" : 0
  },
  "hits" : {
    "total" : 819,
    "max_score" : 0.0,
    "hits" : [ ]
  },
  "aggregations" : {
    "food_bowl" : {
      "value" : 6358.6576502407115
    }
  }
}

这就是我的所作所为,但似乎并没有把它弄好。

val getJson = parse(SearchResponse)
  val getElement = getJson
  for (myValue <- getElement) {
    val ValueResult = myValue.extract("value")

2 个答案:

答案 0 :(得分:0)

假设项目中添加或存在以下依赖项:

  "org.json4s" %% "json4s-core" % "3.5.3",
  "org.json4s" %% "json4s-jackson" % "3.5.3"

我们导入所需的库方法:

import org.json4s.jackson.JsonMethods._
import org.json4s.{DefaultFormats, _}

并定义数据本身:

val json =
    """
      |{
      |  "took" : 3,
      |  "timed_out" : false,
      |  "_shards" : {
      |    "total" : 5,
      |    "successful" : 5,
      |    "failed" : 0
      |  },
      |  "hits" : {
      |    "total" : 819,
      |    "max_score" : 0.0,
      |    "hits" : [ ]
      |  },
      |  "aggregations" : {
      |    "food_bowl" : {
      |      "value" : 6358.6576502407115
      |    }
      |  }
      |}
    """.stripMargin

之后我们提取包含在Option中的原始值:

  implicit val formats = DefaultFormats

  val rawValue = parse(json) \ "aggregations" \ "food_bowl" \ "value" toOption

和模式匹配目标浮点类型:

  rawValue match {
    case Some(JDouble(float)) => println(float)
    case _ => println("Value not present in JSON")
  }

希望它有所帮助!

答案 1 :(得分:0)

解析json后,可以将其解压缩为浮点数

scala> import org.json4s.jackson.JsonMethods.parse
import org.json4s.jackson.JsonMethods.parse
scala> import org.json4s.DefaultFormats
import org.json4s.DefaultFormats
scala>   implicit val formats = DefaultFormats
formats: org.json4s.DefaultFormats.type = org.json4s.DefaultFormats$@4d529dbf
scala> val parsedFloat = (parse(json) \ "aggregations" \ "food_bowl" \ "value").extract[Float]
parsedFloat: Float = 6358.6577