读取Scala中的JSON,其键/值对和类型未知

时间:2018-05-03 06:21:18

标签: json scala

如何在JSON

中迭代without knowing key/value pairs对象Scala及其类型

1 个答案:

答案 0 :(得分:2)

您可以使用常规遍历方法,例如

import cats.syntax.either._
import io.circe._, io.circe.parser._

val json: String = """
  {
    "id": "c730433b-082c-4984-9d66-855c243266f0",
    "name": "Foo",
    "counts": [1, 2, 3],
    "values": {
      "bar": true,
      "baz": 100.001,
      "qux": ["a", "b"]
    }
  }
"""

val doc: Json = parse(json).getOrElse(Json.Null)

val baz: Decoder.Result[Json] =
  cursor.downField("values").downField("baz").as[Json]

解码为Json后,您可以在其上进行模式匹配。

baz.map({
  case JNull       => "Null"
  case JBoolean(_) => "Boolean"
  case JNumber(_)  => "Number"
  case JString(_)  => "String"
  case JArray(_)   => "Array"
  case JObject(_)  => "Object"
})

来源:https://circe.github.io/circe/cursors.htmlhttps://circe.github.io/circe/api/io/circe/Json.htmlhttps://github.com/circe/circe/blob/master/modules/core/shared/src/main/scala/io/circe/Json.scala#L95-L100