Home > Blockchain >  JSON jq - if a key's value matches regex, then create a new key-value pair of existing key-valu
JSON jq - if a key's value matches regex, then create a new key-value pair of existing key-valu

Time:10-15

I have the following json file.

{
  "data": [
    {
      "id": 1,
      "startdate": "2022-10-14 12:05:49",
      "name": "hello1",
      "run_status_index": 29
    },
    {
      "id": 2,
      "startdate": "2022-10-14 11:45:36",
      "name": "hello2",
      "run_status_index": 95
    }
  ]
}

Now, if the name is hello1, then I want to add 18hours to the startdate and create a new key called "endate". For hello2, I want to add 24hours to startdate and create "endate".

So, the output would be...

{
  "data": [
    {
      "id": 1,
      "startdate": "2022-10-14 12:05:49",
      "endate": "2022-10-15 06:05:49",
      "name": "hello1",
      "run_status_index": 29
    },
    {
      "id": 2,
      "startdate": "2022-10-14 11:45:36",
      "endate": "2022-10-15 11:45:36",
      "name": "hello2",
      "run_status_index": 95
    }
  ]
}

I tried the following based on my searches but I cannot wrap my head around the if statements.

jq 'def n: if .data == "" then null else . end; .endate = ((.startdate|n) // "")'

CodePudding user response:

One way:

.data[] |= (
  (.name | if test("hello1") then 18 else 24 end) as $add
  | .enddate = (
      .startdate | strptime("%F %T") | .[3]  = $add | mktime | strftime("%F %T")
    )
)
{
  "data": [
    {
      "id": 1,
      "startdate": "2022-10-14 12:05:49",
      "name": "hello1",
      "run_status_index": 29,
      "enddate": "2022-10-15 06:05:49"
    },
    {
      "id": 2,
      "startdate": "2022-10-14 11:45:36",
      "name": "hello2",
      "run_status_index": 95,
      "enddate": "2022-10-15 11:45:36"
    }
  ]
}

Demo

Note: test implements a regex match. For a simple string comparison .name == "hello1" would suffice.

  • Related