【发布时间】: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
这可能吗?
【问题讨论】: