如何使用jq调整嵌套JSON中info内address与telephone的顺序?
用jq调整JSON嵌套字段的显示顺序
我有一批包含name字段和嵌套info字段的JSON数据,info字段内包含telephone和address两个子字段,现在需要让address显示在telephone之前,请问如何用jq实现?
示例输入
执行命令查看原始数据:
jq . sample.json
输出的原始JSON:
{ "name": "john", "info": { "telephone": "444-5555", "address": "1234 Main st" } } { "name": "jane", "info": { "telephone": "222-3333", "address": "1234 Eagle st" } }
期望输出
{ "name": "john", "info": { "address": "1234 Main st", "telephone": "444-5555" } } { "name": "jane", "info": { "address": "1234 Eagle st", "telephone": "222-3333" } }
错误尝试及结果
我曾尝试以下命令:
jq ". | {name: .name, info: [.info.address, .info.telephone]}" sample.json
但结果把info转成了数组,不符合需求:
{ "name": "john", "info": [ "1234 Main st", "444-5555" ] } { "name": "jane", "info": [ "1234 Eagle st", "222-3333" ] }
正确的jq命令
问题出在你用了数组语法[]来构造info,应该改用对象语法{},明确指定字段的顺序:
jq '{name: .name, info: {address: .info.address, telephone: .info.telephone}}' sample.json
命令解释
- 顶层对象保留
name字段,值为原数据的.name - 重新构造
info对象,先写address字段,再写telephone字段,jq会严格按照你定义的顺序输出对象的键 - 不需要多余的管道符
|,直接构造新对象即可
验证结果
执行上述命令后,输出会完全符合期望:
{ "name": "john", "info": { "address": "1234 Main st", "telephone": "444-5555" } } { "name": "jane", "info": { "address": "1234 Eagle st", "telephone": "222-3333" } }
内容的提问来源于stack exchange,提问作者Battle Mage
相关产品推荐
相关产品推荐

