0

我嵌套了 json 数据,如下所示:

{
  "libraries":[
    {
      "State":"California",
      "genres":[
          {
            "genre":"thriller",
            "books":[
              {
                "title":"Book 1"
              },
              {
                "title":"Book 2"
              }
            ]
          },
          {
            "genre":"mystery",
            "books":[
              {
                "title":"Book 2"
              },
              {
                "title":"Book 3"
              }
            ]
          }
        ]
    },
    {
      "State":"New York",
      "genres":[
          {
            "genre":"horror",
            "books":[
              {
                "title":"Book 2"
              },
              {
                "title":"Book 5"
              }
            ]
          },
          {
            "genre":"comedy",
            "books":[
              {
                "title":"Book 6"
              },
              {
                "title":"Book 7"
              }
            ]
          }
        ]
    }
  ]
}

我正在使用 Scala 中的 jayway jsonpath 库来解析它。我可以使用类似的东西JsonPath.read(myData,"$.libraries[*].genres[*].books[*]")来获取从每个图书馆汇集的所有书籍的数组。我想要的是知道每本书的路径,例如"$.libraries(0).genres(1).books(0)"。有没有办法获得所有书籍路径的数组而不仅仅是所有书籍?

一般来说,我是 jsonpaths 的新手,如果这不是一个好问题,请原谅我。

4

1 回答 1

1

您可以使用配置Option.AS_PATH_LIST

  val conf = Configuration.builder.options(Option.AS_PATH_LIST).build
  val paths = JsonPath.parse(json, conf).read[JSONArray]("$.libraries[*].genres[*].books[*]")
  for(path <- paths.toArray){
    println(path.toString)
  }

在您的示例 json 中给出:

$['libraries'][0]['genres'][0]['books'][0]
$['libraries'][0]['genres'][0]['books'][1]
$['libraries'][0]['genres'][1]['books'][0]
$['libraries'][0]['genres'][1]['books'][1]
$['libraries'][1]['genres'][0]['books'][0]
$['libraries'][1]['genres'][0]['books'][1]
$['libraries'][1]['genres'][1]['books'][0]
$['libraries'][1]['genres'][1]['books'][1]
于 2021-08-26T08:55:03.407 回答