使用 JsLookup 进行多级数组使用 play Json 进行对象列表和简单列表

发布于 2025-01-09 08:24:01 字数 886 浏览 3 评论 0原文

我有一个函数,可以根据我给它的路径从 json 元素列表中提取元素。

函数看起来像这样:

def findAllValuesAtPath(jsValue: JsObject, path: String): List[JsValue] = {
    val jsPath = JsPath(path
      .split("\\[\\*]\\.")
      .flatMap(s => s.split("\\.")
        .map(RecursiveSearch)
      ).toList)
    jsPath(jsValue)
  }

例如:

{
  "person": {
    "kids": [
      {
        "name": "josh",
        "age": 5
      },
      {
        "name": "julia",
        "age": 13
      }
    ]
  }
}

现在如果我给出路径 - “person.kids[*].name”,我将获得他们的名字列表 List("josh", "julia")这就是我想要的。

但如果孩子列表只是简单的列表,例如:

{
  "person": {
    "kids": [
      "josh",
      "julia"
    ]
  }
}

并且我将给出路径 - “person.kids[*]”,我将得到空列表 List() 并且我想将其设为 < code>List("josh", "julia") (不带括号)

您是否有任何方法可以改进我的 func 来处理这两种情况?

i have a function that exctract from a json list of elements based on the path i give it.

the func looks like this:

def findAllValuesAtPath(jsValue: JsObject, path: String): List[JsValue] = {
    val jsPath = JsPath(path
      .split("\\[\\*]\\.")
      .flatMap(s => s.split("\\.")
        .map(RecursiveSearch)
      ).toList)
    jsPath(jsValue)
  }

for example:

{
  "person": {
    "kids": [
      {
        "name": "josh",
        "age": 5
      },
      {
        "name": "julia",
        "age": 13
      }
    ]
  }
}

now if i give the path - "person.kids[*].name" I will get list of their names List("josh", "julia") which its what i want.

but if the list of kids were just simple list like:

{
  "person": {
    "kids": [
      "josh",
      "julia"
    ]
  }
}

and i will give the path - "person.kids[*]" I will get empty list List() and I want to get this as List("josh", "julia") (without the brakets)

do you see any way to improve my func to handle both cases?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文