如何在Bash中将JSON的storagePolicyName字段提升一级?
问题与解决方案
问题描述
我有如下格式的JSON响应对象(注:原始JSON中第一个status字段缺少引号,已修正为合法格式):
{ "storagePoolList": [ { "status": "Online", "statusCode": 0, "storagePolicyEntity": { "_type_": 17, "storagePolicyName": "n1", "storagePolicyId": 38 }, "storagePoolEntity": { "storagePoolName": "n2", "_type_": 160, "storagePoolId": 38 }, "storagePool": { "_type_": 28, "clientGroupId": 38, "clientGroupName": "ddsa" } }, { "status": "Online", "statusCode": 0, "storagePolicyEntity": { "_type_": 17, "storagePolicyName": "dsa", "storagePolicyId": 65 }, "storagePoolEntity": { "storagePoolName": "dasdas", "_type_": 160, "storagePoolId": 65 }, "storagePool": { "_type_": 28, "clientGroupId": 65, "clientGroupName": "fasdf" } } ] }
需求是将数组元素中的storagePolicyName字段从storagePolicyEntity下提升一级,与status字段同级。该JSON存储在data变量中,尝试以下命令后输出无变化:
need_this=$(echo "$data" | jq '.storagePoolList |= map(.storagePolicyName = .storagePolicyEntity.storagePolicyName | del(.storagePolicyEntity))')
解决方案
问题出在原始JSON存在语法错误:第一个数组元素的status值Online未加双引号,属于非法JSON,导致jq无法正常解析处理,因此输出无变化。
修正原始JSON为合法格式后,你的原有命令即可生效,或者也可以使用以下等价写法:
# 写法1:你的原有命令(JSON合法时生效) need_this=$(echo "$data" | jq '.storagePoolList |= map(.storagePolicyName = .storagePolicyEntity.storagePolicyName | del(.storagePolicyEntity))') # 写法2:使用+合并字段的方式 need_this=$(echo "$data" | jq '.storagePoolList |= map(. + {storagePolicyName: .storagePolicyEntity.storagePolicyName} | del(.storagePolicyEntity))')
处理后效果示例
处理后的数组元素结构如下(以第一个元素为例):
{ "status": "Online", "statusCode": 0, "storagePoolEntity": { "storagePoolName": "n2", "_type_": 160, "storagePoolId": 38 }, "storagePool": { "_type_": 28, "clientGroupId": 38, "clientGroupName": "ddsa" }, "storagePolicyName": "n1" }
内容的提问来源于stack exchange,提问作者cesq
相关产品推荐
相关产品推荐

