【问题标题】:JSONPath Export Key & ValueJSONPath 导出键和值
【发布时间】:2022-01-20 09:03:27
【问题描述】:

我正在使用 JSONPath 过滤掉一个 json 文件,我试图从 JSON 数组中检索 Key + Value,但我不知道如何最好地做到这一点。

查询

$.phoneNumbers[*].[type,number]

阵列

{
  "firstName": "John",
  "lastName" : "doe",
  "age"      : 26,
  "address"  : {
  "streetAddress": "naist street",
  "city"         : "Nara",
  "postalCode"   : "630-0192"
 },
 "phoneNumbers": [
  {
     "type"  : "iPhone",
     "number": "0123-4567-8888",
     "address"  : {
        "streetAddress": "naist street",
        "city"         : "Nara",
        "postalCode"   : "630-0192"
  }
},
{
  "type"  : "home",
  "number": "0123-4567-8910",
  "address"  : {
        "streetAddress": "naist street",
        "city"         : "Nara",
        "postalCode"   : "630-0192"
   }
  }
 ]
}

电流输出

[
  "iPhone",
  "0123-4567-8888",
  "home",
  "0123-4567-8910"
]

期望的结果

[
 {
   "type"  : "iPhone",
   "number": "0123-4567-8888",
 },
 {
   "type"  : "home",
   "number": "0123-4567-8910",
 }
]

【问题讨论】:

  • 原始博客文章说,实现应该能够返回值或路径,但不一定同时返回。此外,没有正式的规范(尽管我们正在编写一个),因此实现的支持各不相同。您需要检查您正在使用的实现。
  • 目前 Jayway 实现返回键和值而不是 Goesnner 实现。试试jsonpath.herokuapp.com

标签: jsonpath json-path-expression


【解决方案1】:

您要查找的内容无法使用 JSON Path 完成,因为您要转换数据。 JSON 路径只会为您提供平面列表中的值。

您可能会在 JMES Path 中找到一些运气。这很相似,但我不太熟悉。

【讨论】:

    【解决方案2】:

    您可能需要添加引号

    $.phoneNumbers[*].['type','number']
    

    【讨论】:

    • 那是 Jayway jsonpath 的实现
    • @AkshayG 我不确定我是否理解您的评论。这在许多实现中都是有效的。请参阅JSON Path comparison(搜索Union with keys),特别是Union with keys
    • 我没有说它无效。我说 OPs 查询在最初提出的 gosner 实现中也是有效的。当键是一个单词时,不需要添加引号。但是对于 Jayway,您总是需要在引号中提及键。
    • OP也明确提到了查询的输出,没有提到语法错误。
    • 括号语法需要引号,点语法则不需要。
    猜你喜欢
    • 2017-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多