hruday hruday - 11 months ago 110
JSON Question

find the matching string key and increment its value in json file using bash

A json file has a line in the following format.

"solution-id": 1


And this line is repeated 1000 times in the file. Now I need to modify the line such that file looks like as follows

"solution-id": 1
"solution-id": 2
"solution-id": 3
...
....
.....
""solution-id": 1000"


How can i achieve this using bash or python?

Answer Source

Instead of manipulating JSON with Bash or Python, you could use jq. For example if you have JSON like this:

[
  {
    "solution-id": "foo",
    "junk": "foo"
  },
  {
    "solution-id": "bar",
    "junk": "foo"
  }
]

And you want to transform into this:

[
  {
    "solution-id": 0,
    "junk": "foo"
  },
  {
    "solution-id": 1,
    "junk": "foo"
  }
]

You can write:

jq 'to_entries | map(.value["solution-id"] = .key) | map(.value)' file.json

What's happening here is, the to_entries function takes an array input, and generates key-value pairs, where key is a sequence of numbers 0, 1, 2, ..., n, and value is the original item in the array. The first map in the pipeline is to modify the value with the sequence number, the second map is to extract the value. To understand better, run just jq to_entries' file.json, the mappings will make more sense.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download