I have been looking at trying to get this to work for a number of days but I am stuck.
I have a json data structure with values in it that I want to update, essentially using my json as a database to store configuration values. Here is my JSON:
{
"Actions": [
{
"Number": 1012,
"RollbackPoint": "xxx_1012_RollbackPoint_xxx",
"Parameters": [
{
"Name": "accountType",
"Value": "xxx_1012_accountType_xxx"
},
{
"Name": "userPassword",
"Value": "xxx_1012_userPassword_xxx"
}
]
},
{
"Number": 1015,
"RollbackPoint": "xxx_1015_RollbackPoint_xxx",
"Parameters": [
{
"Name": "accountType",
"Value": "xxx_1015_accountType_xxx"
},
{
"Name": "skipExport",
"Value": "xxx_1015_skipExport_xxx"
}
]
}
]
}
I want to perform two updates
So far the closest I have got to is using this:
cat json.txt | jq '.[] | map(. + {RollbackPoint:(if (."Number") == 1015 then "1015" else .RollbackPoint end)})'
But this strips off the Actions[] element so its no good for me, I don't know where to even start on update 2...
Any help would be greatly appreciated, over 5 hours on google and I am still nowhere near.
Many thanks Matt
jq is equally useful for updating existing JSON data.
jq (as in jq) is a "JSON query language" and might perhaps therefore have been called "JQL" by analogy with "SQL", but jq is shorter :-) Also note that jq is not only a JSON query language, but completely subsumes JSON: any valid JSON expression is a valid jq expression.
A jq program is a "filter": it takes an input, and produces an output. There are a lot of builtin filters for extracting a particular field of an object, or converting a number to a string, or various other standard tasks.
You can make use of the //
operator to mimic (IMHO) nicer if-else trees in conjunction with various filtering filters. Makes it rather easy to follow, compared to a large if-else tree.
.Actions |= map(
(select(.Number == 1015) |
.RollbackPoint = "1012"
) //
(select(.Number == 1012) |
.Parameters |= map((select(.Name == "accountType") | .Value = "AWS") // .)
) //
.
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With