skip to Main Content

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


  1. By using the filters objects and arrays, you can handle different types differently, like here using .[] only on arrays. Then, using -n and inputs lets you access multiple input objects at once, thus collect their values into a single final array.

    jq -n '[inputs.CVE | objects, arrays[] | .ID]'
    

    Demo

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search