如何使用jq将字符串数组转换为指定层级的对象?
使用jq将嵌套数组转换为层级对象
输入结构
[ [ "AppA", "ServiceA", "SecretKey", "topSecretKeyA" ], [ "AppB", "ServiceB", "SecretKey", "topSecretKeyB" ], [ "AppC", "ServiceC", "SecretKey", "topSecretKeyC" ] ]
期望输出结构
{ "AppA": { "ServiceA": { "SecretKey": "topSecretKeyA" } }, "AppB": { "ServiceB": { "SecretKey": "topSecretKeyB" } }, "AppC": { "ServiceC": { "SecretKey": "topSecretKeyC" } } }
实现方案
有两种简洁的jq命令可以完成转换:
方案一:用reduce遍历构建层级
jq 'reduce .[] as $item ({}; .[$item[0]][$item[1]][$item[2]] = $item[3])'
- 初始值设为空对象
{} - 遍历每个子数组
$item,将$item[3]的值依次赋值到三级路径下:$item[0](一级键)→$item[1](二级键)→$item[2](三级键)
方案二:先映射单个层级对象再合并
jq 'map({(.[0]): {(.[1]): {(.[2]): .[3]}}}) | add'
map将每个子数组转换为独立的层级对象add把所有独立对象合并为一个完整结构
关于你之前尝试的命令问题
你之前写的jq 'reduce .[] as $k (null; {($k: .})'存在两个核心问题:
- 把整个子数组当作对象键,没有拆分出三级路径
- 初始值用
null,无法进行层级赋值操作
内容的提问来源于stack exchange,提问作者Mark T
相关产品推荐
相关产品推荐

