Search code examples
jsonjqjsonpath

How do I parse a single record or an array of records in a json field using JsonPath


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?


Solution

  • Use a recursive descent ..:

    $.CVE..ID
    

    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