Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
  "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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading