[英]How to filter and replace values in json with jq
I have problems filtering and updating the content of a json file using jq.我在使用 jq 过滤和更新 json 文件的内容时遇到问题。 I need to filter json data based on specific values, and based on that filter edit other values and increment others
我需要根据特定值过滤 json 数据,并基于该过滤器编辑其他值并增加其他值
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:过滤但结果缺少顶部键“x-ID.0”信息,结果如下:
{
"_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为了重新编号,我已经测试了下面的 function 并且效果很好
jq -n -s '[ foreach inputs[] as $i (100; .+1; $i*{"x-channelID":(.-1)}) ]'
Here is the original json file这是原始的 json 文件
{
"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 !谢谢你的帮助 !
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. to_entries
map 将您的 object 放入{ key: "key", value: "value" }
项的数组中。
map(select(filter))
filter those whose value match your criteria. map(select(filter))
过滤那些值符合您的条件的人。
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.然后,我们使用
foreach
来增加一个计数器,同时迭代剩余的键/值对,并用计数器更新值的 x-channelID 字段。
Finally we use from_entries
to recreate the desired object from the array of key/value pairs.最后,我们使用
from_entries
从键/值对数组中重新创建所需的 object。
You can try it here .你可以在这里试试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.