Sunday, October 24, 2021

[SOLVED] delete repeating 1:M representations in JSON files

Issue

I have about 700 JSON files, with repeating vulnerabilities like:

{
  "vulnerabilities": [
}
{
  "vulnerabilities": [
}

This json representation is showing vulnerabilities occurring. I want to delete everything after the first vulnerabilities {} occurrence for each file. So I want each json then saved with this representation:

{
  "vulnerabilities": [
}

I have a loop:

for file in *.json; do
# logic
done

that loops through all json files currently and does logic to them.

How can I achieve deleting everything in each json file after the first occurrence of vulnerabilities { }


Solution

If you have valid JSON such as:

[
  {
    "vulnerabilities": [ {"issue":"root access"}, {"timestamp":"2021-04-19T20:27:23+00:00"} ]
  },
  {
    "vulnerabilities": [ {"issue":"something else"}, {"timestamp":"2021-04-18:27:23+00:00"}]
  }
]

and you have jq on your system then it's a simple as:

jq '.[0]' vulnerabilities.json

to get:

{
  "vulnerabilities": [
    {
      "issue": "root access"
    },
    {
      "timestamp": "2021-04-19T20:27:23+00:00"
    }
  ]
}


Answered By - stdunbar