如何使用jq将此嵌套对象转换为展平对象?

时间:2017-06-29 22:42:14

标签: json object key jq flatten

我需要使用jq将此输入转换为未连接的对象。在Python中,我可以按照以下方式正确转换它。

output = {(k1 + '-' + k2): v2 for k1, v1 in input.iteritems() for k2, v2 in v1.iteritems()}

但我无法弄清楚如何在jq中执行此操作。操作嵌套对象的文档很差。

{
    "group1-permission": {
        "address": "test1",
        "others": "test2",
        "packet-capture": "test3",
        "policy": "test4",
        "schedule": "test5",
        "service": "test6"
    },
    "group2-permission": {
        "config": "none",
        "data-access": "none",
        "report-access": "none",
        "threat-weight": "none"
    },
    "group3-permission": {
        "antivirus": "none",
        "application-control": "none",
        "casi": "none",
        "data-loss-prevention": "none",
        "dnsfilter": "none",
        "icap": "none",
        "ips": "none",
        "spamfilter": "none",
        "voip": "none",
        "waf": "none",
        "webfilter": "none"
    }
}

输出应如下所示:

{
    "group1-permission-address": "test1",
    "group1-permission-others": "test2",
    "group1-permission-packet-capture": "test3",
    "group1-permission-policy": "test4",
    "group1-permission-schedule": "test5",
    "group1-permission-service": "test6",
    "group2-permission-config": "none",
    "group2-permission-data-access": "none",
    "group2-permission-report-access": "none",
    "group2-permission-threat-weight": "none",
    "group3-permission-antivirus": "none",
    "group3-permission-application-control": "none",
    "group3-permission-casi": "none",
    "group3-permission-data-loss-prevention": "none",
    "group3-permission-dnsfilter": "none",
    "group3-permission-icap": "none",
    "group3-permission-ips": "none",
    "group3-permission-spamfilter": "none",
    "group3-permission-voip": "none",
    "group3-permission-waf": "none",
    "group3-permission-webfilter": "none"
}

1 个答案:

答案 0 :(得分:4)

在我看来,文档非常好,但有助于熟悉 /*flex-container*/ #header { position: fixed; display: flex; flex-wrap: wrap; background-color: #343434; top: 0; right: 0; left: 0; height: auto; padding-left: 10px; padding-right: 10px; padding-bottom: .3%; padding-top: .3%; border-bottom: 1px solid white; z-index: 1000; } /*flex-childs*/ /*table*/ #login { margin-left: auto; } /*td*/ #users { width: 100%; border: 1px solid #ccc; box-shadow: 0px 0px 5px black; border-radius: 1px; font-size: 12px; padding: 2px 2px 2px 2px; } /*td*/ #pass { width: 100%; border: 1px solid #ccc; box-shadow: 0px 0px 5px black; border-radius: 1px; font-size: 12px; padding: 2px 2px 2px 2px; } /*td*/ #register { font-size: 17.5px; } 以及管道和过滤器的一些舒适度。无论如何,这是一个面向地图的解决方案:

map

这是另一个,适用于任意深度嵌套的JSON对象和数组:

to_entries
| map( .key as $key
       | .value
       | to_entries
       | map ( { ($key + "-" + .key): .value } ) | add ) | add

这里当然有一个警告:如果路径因使用“ - ”作为连接字符而发生碰撞,则某些数据可能会丢失。