从JSON文件

时间:2015-05-19 15:55:12

标签: json scala

我正在处理带有嵌套对象的JSON文件,并且想要提取子对象而不将它们转换为与Scala case类等价的对象。是否有任何预先构建的功能可以通过这种方式过滤出JSON文本块?

例如,如果我有一个内容与此类似的JSON文件:

{
  "parentObject": "bob",
  "parentDetail1": "foo",
  "subObjects": [
    {
      "childObjectName": "childname1",
      "detail1": "randominfo1",
      "detail2": "randominfo1"
    },
    {
      "childObjectName": "childname2",
      "detail1": "randominfo2",
      "detail2": "randominfo2"
    },
    {
      "childObjectName": "childname3",
      "detail1": "randominfo3",
      "detail2": "randominfo3"
    }
  ]
}

我想提取subObjects节点,理想情况下是单个JSON文本块(可能是一个String Array,每个subObject作为一个元素)。我知道我可以将整个JSON文件解析为我在Scala类中预先定义的对象,但宁愿不采用该路由,因为对于较大的文件来说这可能太昂贵了。 我正在寻找一种简单而优雅的方式来到这里。有什么想法吗?

2 个答案:

答案 0 :(得分:2)

解决方案使用json-lenses和喷json

import spray.json.DefaultJsonProtocol._
import spray.json._
import spray.json.lenses.JsonLenses._

object Main extends App {

 val jsonData =
   """
     |{
     |  "parentObject": "bob",
     |  "parentDetail1": "foo",
     |  "subObjects": [
     |    {
     |      "childObjectName": "childname1",
     |      "detail1": "randominfo1",
     |      "detail2": "randominfo1"
     |    },
     |    {
     |      "childObjectName": "childname2",
     |      "detail1": "randominfo2",
     |      "detail2": "randominfo2"
     |    },
     |    {
     |      "childObjectName": "childname3",
     |      "detail1": "randominfo3",
     |      "detail2": "randominfo3"
     |    }
     |  ]
     |}
   """.stripMargin.parseJson


  val subObjectsLens = 'subObjects / *

  val subObjects = jsonData.extract[JsValue](subObjectsLens)

  println(subObjects map {_.compactPrint} mkString ", ")
}

答案 1 :(得分:0)

大多数JSON库提供某种功能来提取嵌套的JSON。你还没有正确地提到你想要输出的方式(String Array与每个subObject作为一个元素?你想把subObject的字段合并成一个字符串??),我将留下答案提取嵌套的JSON。

JSON4s

val json = parse(""" {
                    "parentObject": "bob",.... }""")
val subObjects = (json \"subObjects") 
// Returns a JArray(internal representation of JSON Array in Json4s). It has a flexible DSL
//which you can use to extract the fields as you like. 

Play-Json

val json = Json.parse("""{ "parentObject": "bob",.... }""")
val subObjects = (json \"subObjects")
//>subObjects  : play.api.libs.json.JsValue =  [{"childObjectName":"childname1", "detail1":"randominfo1", ....

其他图书馆也应该有类似的功能。