I have a json value that can contain a single record or an array, I need to extract the ID field of these records and gather them in an array. The resulting element should be an array with 1 or more ID values.
Input 1 Single record
{
"CVE": {
"ID": "CVE-2022-26138","URL": "foo.bar" }
}
Input 2 An array of two records
{
"CVE": [
{ "ID": "CVE-2019-2969","URL": "foo.com" },
{ "ID": "CVE-2019-3030","URL": "bar.com" }
]
}
I tried the JSONPath expression $.CVE.ID
which results in ["CVE-2022-26138"]
for Input 1 but returns empty array on the Input 2.
Then I tried the JSONPath expression $.CVE.*.ID
which results in empty array [] for Input 1 but gives me correct output for Input 2 ["CVE-2019-2969", "CVE-2019-3030"]
My question is, is there a single JSONPath expression I can use that gives me non-empty result in either input?
2
Answers
By using the filters
objects
andarrays
, you can handle different types differently, like here using.[]
only on arrays. Then, using-n
andinputs
lets you access multiple input objects at once, thus collect their values into a single final array.Demo
Use a recursive descent
..
:Note, however, that if your objects contain nested
ID
properties, this will pick up those as well.Try it out at https://json-everything.net/json-path