Reputation: 27
I'm trying to add values to a specific key inside a specific array element using jq. I have the following JSON:
[
{
"name":"element1",
"properties":{
"hardwareProfile":{
"vmSize":"vm_size"
}
}
},
{
"name":"element2",
"properties":{
"hardwareProfile":{
"vmSize":"vm_size"
}
}
}
]
And I'd like to add information to the properties.hardwareProfile
key inside the first element so it becomes:
[
{
"name":"element1",
"properties":{
"hardwareProfile":{
"vmSize":"vm_size",
"newProperty":"new_value",
"anotherNewProperty":"another_new_value"
}
}
},
{
"name":"element2",
"properties":{
"hardwareProfile":{
"vmSize":"vm_size"
}
}
}
]
I've had limited success adding the information doing this:
$ VM_SIZE_INFO="{newProperty:\"new_value\", anotherNewProperty:\"another_new_value\"}"
$ jq "[.[0].properties.hardwareProfile + $VM_SIZE_INFO]" resources.json
[
{
"vmSize": "Standard_B8ms",
"newProperty": "new_value",
"anotherNewProperty": "another_new_value"
}
]
But this doesn't really work for me since I need the full json on the output.
How can I do this? Thanks!
Upvotes: 2
Views: 644
Reputation: 85800
Your idea was right, but by virtue of using +
on the object at first index, you lost the objects at other indices. You need to use the append operator +=
If its the "first" object to be added, use the object designator .[0]
to add the records of your choice.
Also using a shell variable with double quotes is not a right way to import JSON shell content to your jq
program. Use the --argjson
option to import directly
jq --argjson new '{ "newProperty":"new_value", "anotherNewProperty":"another_new_value" }' \
'.[0].properties.hardwareProfile += $new' json
or with a variable wrapping the JSON content under single quotes
VM_SIZE_INFO='{ "newProperty":"new_value", "anotherNewProperty":"another_new_value" }'
and doing
jq --argjson new "$VM_SIZE_INFO" '.[0].properties.hardwareProfile += $new' json
Upvotes: 2