Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JSON+jq – if a key's value matches regex, then create a new key-value pair of existing key-value by formatting date

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…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
  "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) // "")'

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading