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

Replace null values from a select command in jq with the value of another field

Goal is to search for null values of part_description and insert in part field value.

[
  {
    "part": "brake-01982",
    "part_description": null,
  }
]

Expected Output

[
  {
    "part": "brake-01982",
    "part_description": "brake-01982",
  }
]

Command:
jq ‘(.[] | select(.part_description==null).part_description) |= .part’

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

Results in no change

What does work is if I try to insert a string value. The double quoted string results in what I would expect. Demo below. How do I pass another fields value into this command vs a quoted string?

Command: jq ‘(.[] | select(.part_description==null).part_description) |= "test"’

Demo

Output

[
  {
    "part": "brake-01982",
    "part_description": "test"
  }
]

>Solution :

The alternative operator // takes on the second value if the first one is null, false, or empty (i.e. missing). Combined with the update operator |=, this can be contracted to //=.

jq '.[] |= (.part_description //= .part)'
[
  {
    "part": "brake-01982",
    "part_description": "brake-01982"
  }
]

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