2

我是 scala 开发的新手,也许这里是重复的问题,试图通过 circe lib 解析 json,我知道如何解析 json 以从中获取特定值,但我想通过为任何 json 提供 json 路径来动态地解析它。例如,我们在下面有这个json,就像输入一样,还有这样的json路径$.store.book[*].author

{
    "store": {
        "book": [
            {
                "category": "reference",
                "author": "Nigel Rees",
                "title": "Sayings of the Century",
                "price": 8.95
            },
            {
                "category": "fiction",
                "author": "Evelyn Waugh",
                "title": "Sword of Honour",
                "price": 12.99
            },
            {
                "category": "fiction",
                "author": "Herman Melville",
                "title": "Moby Dick",
                "isbn": "0-553-21311-3",
                "price": 8.99
            },
            {
                "category": "fiction",
                "author": "J. R. R. Tolkien",
                "title": "The Lord of the Rings",
                "isbn": "0-395-19395-8",
                "price": 22.99
            }
        ],
        "bicycle": {
            "color": "red",
            "price": 19.95
        }
    },
    "expensive": 10
}

和输出将是这样的:

[
   "Nigel Rees",
   "Evelyn Waugh",
   "Herman Melville",
   "J. R. R. Tolkien"
]

通过使用 jayway,我可以轻松地做到这一点,但我想通过使用 circe 来做到这一点。下面我使用 jayway 的代码

val fileStream = getClass.getResourceAsStream("/sample_json.json")
var rawJson: String = Source.fromInputStream(fileStream).getLines.mkString.stripMargin
val jsonPath: String = "$..book[2]"
val result = JsonPath.read[AnyVal](rawJson, jsonPath)
4

0 回答 0