使用jq从其他数组派生数组(参见Python列表推导)

时间:2017-07-01 01:00:33

标签: arrays json jq blacklist

鉴于以下json包含两个数组:

function getContextualSignature(node: FunctionExpression | ArrowFunction | MethodDeclaration): Signature {
    Debug.assert(node.kind !== SyntaxKind.MethodDeclaration || isObjectLiteralMethod(node));
    const type = getContextualTypeForFunctionLikeDeclaration(node);
    if (!type) {
        return undefined;
    }
    if (!(type.flags & TypeFlags.Union)) {
        return getNonGenericSignature(type, node);
    }
    let signatureList: Signature[];
    const types = (<UnionType>type).types;
    for (const current of types) {
        const signature = getNonGenericSignature(current, node);
        if (signature) {
            if (!signatureList) {
                // This signature will contribute to contextual union signature
                signatureList = [signature];
            }
            else if (!compareSignaturesIdentical(signatureList[0], signature, /*partialMatch*/ false, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true, compareTypesIdentical)) {
                // Signatures aren't identical, do not use
                return undefined;
            }
            else {
                // Use this signature for contextual union signature
                signatureList.push(signature);
            }
        }
    }

我希望派生第三个数组,其中包含第一个数组中出现的项而不是第二个数组:

{"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":["dev02","dev03","dev04","dev07","dev09"]} 用于此任务

在python中,我会使用列表推导来实现这个目的:

jq

我目前正在尝试使用>>> 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'] 循环遍历array1中的项目,并使用foreach检查它们是否存在于array2中,但我正在努力学习语法。

如何使用in实现此目的?

1 个答案:

答案 0 :(得分:1)

来自jq manual

  

除了数字上的常规算术减法, - 运算符   可以在数组上使用,以删除第二个数组的所有出现   来自第一个数组的元素。

这样做:

jq '{ "enabled_zones": (.zones - .disabled_zones) }' data.json