如何使用圆形光学解析嵌套的Json阵列

Kno*_*uch 2 scala lenses circe

我阅读了使用Circe Optics的Circe文档给出的示例。文档中的示例非常简单,因为到节点的路径很容易找到。

在我的情况下,json看起来像

import io.circe._, io.circe.parser._

val json = """[["a",{"entity":["foo"]}],["b",{"entity":["bar"]}]]"""
Run Code Online (Sandbox Code Playgroud)

这是有效的json,我可以解析使用 parse(json)

但是,我该如何编写镜头以便提取所有“ foo”,“ bar”。

Tra*_*own 6

If you want the fancy JsonPath style, you can use each to select every matching member of a JSON array, so your path could look like this:

import io.circe.optics.JsonPath

val entities = JsonPath.root.each.each.entity.each.string
Run Code Online (Sandbox Code Playgroud)

And then supposing you have the following Json value:

import io.circe.jawn.parse

val Right(json) = parse("""[["a",{"entity":["foo"]}],["b",{"entity":["bar"]}]]""")
Run Code Online (Sandbox Code Playgroud)

You could use the Traversal path like this:

scala> entities.getAll(json)
res0: List[String] = List(foo, bar)

scala> entities.modify(_ * 2)(json).noSpaces
res1: String = [["a",{"entity":["foofoo"]}],["b",{"entity":["barbar"]}]]

scala> entities.set("___")(json).noSpaces
res2: String = [["a",{"entity":["___"]}],["b",{"entity":["___"]}]]
Run Code Online (Sandbox Code Playgroud)

You could also construct the path explicitly, but it'd involve a lot more code.