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

jq .[] removes objects from array when updating value for a key

I am trying to update an value for a key based on a select filter. The list contains dictionaries with same key names, but different values. Based on value, I am filtering to select a dictionary and then update the sibling key in it.

The value update works, but the dictionaries move out of list as expected because of .[], but how do I add them back to the list. Or, how can I do it without using .[]?

Input List:

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

[
    {
        "key1": "a",
        "key2": "b"
    },
    {
        "key1": "c",
        "key2": "d"
    },
    {
        "key1": "d",
        "key2": "e"
    }
]

Command I am running:
jq --arg temp "f" '.[] | select( .key1 == "c").key2 |= $temp' test.json

output:

{
  "key1": "a",
  "key2": "b"
}
{
  "key1": "c",
  "key2": "f"
}
{
  "key1": "d",
  "key2": "e"
}

The objects are not part of list now.
Expected output:

[
    {
        "key1": "a",
        "key2": "b"
    },
    {
        "key1": "c",
        "key2": "f"
    },
    {
        "key1": "d",
        "key2": "e"
    }
]

How can we add the objects back to a list, or do it in-place.

>Solution :

Use map() to keep the original structure:

jq --arg temp  "f" 'map(select( .key1 == "c").key2 |= $temp)' test.json

Online 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