[英]Deriving an array from other arrays with jq (cf. Python list comprehensions)
Given the following json containing two arrays: 给定以下json,其中包含两个数组:
{"zones":["dev01","dev02","dev03","dev04","dev05","dev06","dev07","dev08","dev09","dev10","dev11","dev12","dev13","dev14","dev15","dev16","dev17","dev18","dev19","dev20"],"disabled_zones":["dev01","dev05","dev06","dev08","dev10","dev11","dev12","dev13","dev14","dev15","dev16","dev17","dev18","dev19","dev20"]}
I wish to derive a third array containing items that occur in the first array but not the second: 我希望派生第三个数组,其中包含在第一个数组中出现但不在第二个数组中的项:
{"enabled_zones":["dev02","dev03","dev04","dev07","dev09"]}
I would like to use jq
for this task 我想使用
jq
完成此任务
In python I would use a list comprehension to achieve this: 在python中,我将使用列表推导来实现此目的:
>>> zones = ["dev01","dev02","dev03","dev04","dev05","dev06","dev07","dev08","dev09","dev10","dev11","dev12","dev13","dev14","dev15","dev16","dev17","dev18","dev19","dev20"]
>>> disabled_zones = ["dev01","dev05","dev06","dev08","dev10","dev11","dev12","dev13","dev14","dev15","dev16","dev17","dev18","dev19","dev20"]
>>> enabled_zones = [x for x in zones if x not in disabled_zones]
>>> print(enabled_zones)
['dev02', 'dev03', 'dev04', 'dev07', 'dev09']
I am currently trying to loop over items in array1 using foreach
and checking if they exist in array2 using in
but I'm struggling with the syntax. 我目前正在尝试使用
foreach
array1中的项目,并使用in
检查它们是否存在于array2中in
但是我在语法上苦苦挣扎。
How can I achieve this using jq
? 我如何使用
jq
实现呢?
As well as normal arithmetic subtraction on numbers, the - operator can be used on arrays to remove all occurrences of the second array's elements from the first array.
除了对数字进行常规算术减法外,-运算符还可用于数组,以从第一个数组中删除所有出现的第二个数组元素。
this would do : 这会做:
jq '{ "enabled_zones": (.zones - .disabled_zones) }' data.json
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.