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

Transform specific fields into array(s) using jq

Given the following JSON:

{
  "one": "1",
  "two": "2",
  "flag": "f1 f2 f3",
  "test one": "",
  "test two": "",
  "test three": ""
}

Is it possible to obtain the following result using jq?

{
  "one": "1",
  "two": "2",
  "flags": ["f1", "f2", "f3"],
  "tests": ["one", "two", "three"]
}

Three points are crucial:

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

  1. Leave unchanged any field that is not flag or starts with test

  2. Transform flag (space separated values) into an array

  3. Any field that starts with test is added to an array (tests) where the value is the remaining part of the field’s name

>Solution :

You can use /= to update by splitting, startswith to match at the beginnning of a string, and to_entries and with_entries to manipulate entries involving the key name:

jq '
  .flag /= " "
  | .tests = (to_entries | map(.key | select(startswith("test "))[5:]))
  | with_entries(select(.key | startswith("test ") | not))
'
{
  "one": "1",
  "two": "2",
  "flag": [
    "f1",
    "f2",
    "f3"
  ],
  "tests": [
    "one",
    "two",
    "three"
  ]
}

Demo

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