如何使用XPATH \ JSONPATH选择一个名为“forecast_XXX”的JSON对象?

时间:2018-03-29 09:00:08

标签: json xpath jsonpath

我不是 XPATH ,我有以下问题。

我有这个JSON对象:

{
    "forecast_1": {
        "country": "Rwanda",
        "forecast_date": "2018-03-20",
        "province": "Kigali City",
        "district": "Kigali",
        "morning": {
            "min_temp": 14,
            "status": "Sun with right rain",
            "max_temp": 16,
            "humidity": "",
            "wind_direction": "",
            "wind_force": "",
            "description": "Lorem ipsum"
        },
        "afternoon": {
            "min_temp": 24,
            "status": "Dark cloud with rain",
            "max_temp": 28,
            "humidity": "",
            "wind_direction": "",
            "wind_force": "",
            "description": "Lorem ipsum"
        }
    },
    "forecast_2": {
        "country": "Rwanda",
        "forecast_date": "2018-03-25",
        "province": "Kigali",
        "district": "Kigali",
        "morning": {
            "min_temp": 21,
            "status": "Rain showers",
            "max_temp": 21,
            "humidity": "",
            "wind_direction": "",
            "wind_force": "",
            "description": "There will be heavy rain"
        },
        "afternoon": {
            "min_temp": 32,
            "status": "Rain showers",
            "max_temp": 32,
            "humidity": "",
            "wind_direction": "",
            "wind_force": "",
            "description": "There will be heavy rain with thunder"
        }
    }
}

你可以看到它包含由 forecast_XXX 标识的2个“根”对象(但可以超过2个),在特定情况下我有 forecast_1 forecast_2

所以我可以拥有像这样的JSON对象的集合,但是没有JSON数组(它们来自外部Web服务,我不能将它们放在数组中)。

所以我需要一个 XPATH 表达式来识别所有这些 forecast_XXX 对象(所以我可以尝试迭代这些对象,好像这些对象在数组中一样)。

如何使用XPATH表达式选择所有这些 forecast_XXX 对象?我在哪里可以测试它? (它应该存在一些在线工具,我放置了JSON和我的XPATH表达式并获得了输出)

1 个答案:

答案 0 :(得分:1)

要使用XPath选择JSON结构,需要XPath 3.1。 (我将JsonPath的答案留给其他人。)

使用forecast_N密钥是进行数据设计的一种不幸方式,但可以按以下方式处理:

map:keys()[$json, matches('.', 'forecast_[0-9]+')]!map:get($json, .)

假设$json是使用parse-json()json-doc()解析JSON输入的结果。

如果您的XPath 3.1引擎支持更高阶的功能,那么您也可以

map:for-each($json, 
    function($k, $v){$v[matches($k, 'forecast_[0-9]+')]})