【问题标题】:Jsonpath expression to select a string or an array用于选择字符串或数组的 Jsonpath 表达式
【发布时间】:2016-12-22 18:44:01
【问题描述】:

我有一些 JSON 数据,其中包含一个数组元素;但是,当数组只包含一个元素时,信息会以字符串而不是数组的形式提供。请参阅下面的 $.phoneNumbers.type 元素。在第一个电话号码中,“type”元素表示为一个数组,但该数组仅包含一个元素(“iPhone”)。在第二个电话号码中,类型只是一个简单的字符串(“home”)。

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

当我尝试使用 JSONPath 解析这个表达式时:

$.phoneNumbers[0].type[0]

当元素未包含在数组括号中时,我收到以下错误。

Filter: [0] can only be applied to arrays. Current context is: home - Line: 0"

是否有可以成功解析其中任何一个的 JSONPath 表达式?基本上,我认为我需要先检查元素是数组还是字符串,然后根据需要进行调整,如下所示:

如果是数组: $.phoneNumbers[0].type[0]

如果是字符串: $.phoneNumbers[0].type

这可能吗?

【问题讨论】:

    标签: arrays json jsonpath


    【解决方案1】:

    当使用带有https://jsonpath.curiousconcept.com 的 JSON 输入时,我可以使用以下 JSONPath 查询来获取“iPhone”和“home”值:$.phoneNumbers[*].type

    【讨论】:

      猜你喜欢
      • 2013-03-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-16
      • 2016-08-26
      • 1970-01-01
      • 2019-06-16
      • 2023-01-11
      相关资源
      最近更新 更多