1

I have problems filtering and updating the content of a json file using jq. I need to filter json data based on specific values, and based on that filter edit other values and increment others

I have tried to use

jq '.[] | select (."name"| contains("CHANNEL1"))' 

to filter but the result is missing the top key "x-ID.0" info, the result is the following :

{
  "_file.name": "filename.ext",
  "name": "CHANNEL1 HD TV",
  "logo": "file.png",
  "x-channelID": "726"
}
{
  "_file.m3u.name": "filename.ext",
  "name": "CHANNEL1 SD",
  "logo": "file.png",
  "x-channelID": "726"
}

For renumbering i have tested the function below and it works well

jq -n -s '[ foreach inputs[] as $i (100; .+1; $i*{"x-channelID":(.-1)}) ]'

Here is the original json file

{
  "x-ID.0": {
    "_file.name": "filename.ext",
    "name": "CHANNEL1 HD TV",
    "logo": "file.png",
    "x-channelID": "726"
  },
   "x-ID.2": {
    "_file.m3u.name": "filename.ext",
    "name": "CHANNEL2",
    "logo": "file.png",
    "x-channelID": "106"
  },
   "x-ID.3": {
    "_file.m3u.name": "filename.ext",
    "name": "CHANNEL3 SD",
    "logo": "file.png",
    "x-channelID": "236"
  },
   "x-ID.4": {
    "_file.m3u.name": "filename.ext",
    "name": "CHANNEL1 SD",
    "logo": "file.png",
    "x-channelID": "726"
  },
   "x-ID.5": {
    "_file.m3u.name": "filename.ext",
    "name": "CHANNEL2 HD",
    "logo": "file.png",
    "x-channelID": "726"
  }
}

here is the expected the result

{
  "x-ID.0": {
    "_file.m3u.name": "filename.ext",
    "name": "CHANNEL1 HD",
    "logo": "CHANNEL1.png",
    "x-channelID": "100"
  },
   "x-ID.4": {
    "_file.m3u.name": "filename.ext",
    "name": "CHANNEL1 SD",
    "logo": "CHANNEL1.png",
    "x-channelID": "101"
  }
}

Thanks for your help !

Hidea
  • 13
  • 5

1 Answers1

0

You can use the following :

to_entries | map(select(.value.name|strings|contains("CHANNEL1"))) | [foreach .[] as $keyvalue (99; .+1; { key: $keyvalue.key, value: ($keyvalue.value + {"x-channelID": .})})] | from_entries

to_entries map your object into an array of { key: "key", value: "value" } items.

map(select(filter)) filter those whose value match your criteria.

We then use foreach to increment a counter while we iterate over the remaining key/value pairs and update the x-channelID field of the values with the counter.

Finally we use from_entries to recreate the desired object from the array of key/value pairs.

You can try it here.

Aaron
  • 24,009
  • 2
  • 33
  • 57
  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/202106/discussion-on-answer-by-aaron-how-to-filter-and-replace-values-in-json-with-jq). – Samuel Liew Nov 09 '19 at 20:45