gpt4 book ai didi

json - 如何使用 jq 将这个嵌套对象转换为扁平对象?

转载 作者:行者123 更新时间:2023-12-05 02:18:36 24 4
gpt4 key购买 nike

我需要使用 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"
}

最佳答案

在我看来,该文档非常出色,但它有助于熟悉 map 以及对管道和过滤器的一些舒适度。不管怎样,这是一个面向 map 的解决方案:

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

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

[paths(scalars) as $path | { ($path|join("-")): getpath($path) }] | add

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

关于json - 如何使用 jq 将这个嵌套对象转换为扁平对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44836049/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com