Reputation: 42997
I am not so into XPATH and I have the following problem.
I have this JSON object:
{
"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"
}
}
}
as you can see it contains 2 "root" object identified by forecast_XXX (but can be more than 2), in the specific case I have forecast_1 and forecast_2.
So I can have a collection of JSON objects like these but there are not into a JSON array (they come from an external web service and I can not have them inside an array).
So I need an XPATH expression that identifies all these forecast_XXX objects (so I can try to iterate on these objects as if thse object were inside an array).
How can I select all these forecast_XXX objects using XPATH expression? And where can I test it? (it should exist some online tool where I put the JSON and my XPATH expression and I obtain the output)
Upvotes: 0
Views: 50
Reputation: 163458
For selection into JSON structures using XPath, you need XPath 3.1. (I'll leave a JsonPath answer to others.)
This use of forecast_N
keys is an unfortunate way of doing the data design, but it can be handled as:
map:keys()[$json, matches('.', 'forecast_[0-9]+')]!map:get($json, .)
Assuming $json
is the result of parsing the JSON input using parse-json()
or json-doc()
.
If your XPath 3.1 engine supports higher order functions then you could also do
map:for-each($json,
function($k, $v){$v[matches($k, 'forecast_[0-9]+')]})
Upvotes: 1