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