如何使用JQ转换结构复杂的JSON对象数组?
JSON结构转换解决方案
原始JSON结构
{ "name": "My Team", "team size": [ { "min": [ { "Leader": 1 }, { "Followers": 5 }, { "point cost": 7 } ] }, { "max": [ { "Leader": 1 }, { "Followers": 9 }, { "point cost": 11 } ] } ] }
目标JSON结构
{ "name": "My Team", "team size": [ { "size": "min", "Leader": 1, "Followers": 5, "point cost": 7 }, { "size": "max", "Leader": 1, "Followers": 9, "point cost": 11 } ] }
正确的jq命令
jq '.["team size"] |= map(to_entries[] | {size: .key} + (.value | add))' input.json
命令说明
.["team size"] |=:定位到team size字段并修改其内容map(...):遍历team size数组里的每个元素to_entries[]:将单个对象(如{"min": [...]})转为键值对格式({"key": "min", "value": [...]}){size: .key}:生成包含size字段的对象,值为原键名(min/max).value | add:把数组内的多个零散对象(如{"Leader":1})合并成一个完整对象+:将size对象和合并后的属性对象拼接为最终结构
内容的提问来源于stack exchange,提问作者OnlyDean
相关产品推荐
相关产品推荐

