Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having trouble searching and replacing in my JSON using jq

Tags:

json

jq

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

  1. Update RollbackPoint to "1012" where Number = 1015
  2. Update value to "AWS" where name = "accountType" under Parameters, where Number = 1012

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

like image 305
msmithwr Avatar asked Apr 12 '15 17:04

msmithwr


People also ask

Can jq edit JSON?

jq is equally useful for updating existing JSON data.

What does jq stand for JSON?

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.

What is jq query?

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.


1 Answers

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") // .)
    ) //
    .
)
like image 178
Jeff Mercado Avatar answered Sep 29 '22 12:09

Jeff Mercado