I want to specify a serial number in the JSON element of the shell script.

Asked 2 years ago, Updated 2 years ago, 110 views

Current state

We are currently working on correcting JSON and adding a new Val element (Key: Value) from the existing JSON.

Current Code

{
  "total": [
      {
        "name": "sasuke",
        "category": "animal",
        "URL": "https://0000/0000/0000"
      },
       {
        "name": "siro",
        "category": "animal",
        "URL": "https://1111/1111/1111"
      },
       {
        "name": "kuro",
        "category": "animal",
        "URL": "https://2222/2222/2222"
      }
   ]
}

Problems

When adding a new Val element (Key:Value) to JSON, I would like to fill in the Value.
To add an element

|jq'.liveInfo[0]|=.+{"number":continuous}' 

I understand that can be realized in , but I don't know how to write the code for the serial number.
Please let me know.

Here's the code you want to achieve:

Additional Elements

"number": "continuous number"

Completed code

{
  "total": [
      {
    "number": "1"
        "name": "sasuke",
        "category": "animal",
        "URL": "https://0000/0000/0000",
      },
       {
    "number": "2"
        "name": "siro",
        "category": "animal",
        "URL": "https://1111/1111/1111",
      },
       {
    "number"—"3"
        "name": "kuro",
        "category": "animal",
        "URL": "https://2222/2222/2222",
      }
   ]

json shellscript jq

2022-09-30 15:55

2 Answers

The following is how to use reduce.

$jq-r'
    reduction range (.total | length) as $i(.; .total[$i].number="\($i+1)")
  ' data.json
{
  "total": [
    {
      "name": "sasuke",
      "category": "animal",
      "URL": "https://0000/0000/0000",
      "number": "1"
    },
    {
      "name": "siro",
      "category": "animal",
      "URL": "https://1111/1111/1111",
      "number": "2"
    },
    {
      "name": "kuro",
      "category": "animal",
      "URL": "https://2222/2222/2222",
      "number"—"3"
    }
  ]
}


2022-09-30 15:55

It's easy to process with awk if you want to separate it from text processing.
"name"—When you find a line that contains , printf prints the serial number as a value with the name number.

awk'
US>BEGIN{
    no = 1
}
/\"name\":/{
    printf("\"number\":\"%d\",\n", no++)
}
{
    print$0
}
' json file

[Output Results]

{
  "total": [
      {
        "number": "1",
        "name": "sasuke",
        "category": "animal",
        "URL": "https://0000/0000/0000"
      },
       {
        "number": "2",
        "name": "siro",
        "category": "animal",
        "URL": "https://1111/1111/1111"
      },
       {
        "number": "3",
        "name": "kuro",
        "category": "animal",
        "URL": "https://2222/2222/2222"
      }
   ]
}


2022-09-30 15:55

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.