如何从JSON数组提取指定属性?含billing中first_name的jq命令修正
提取JSON订单信息的正确jq命令
问题背景
你有一份存储订单信息的JSON数组文件,需要提取其中的id、status(曾误写为satus)、total字段,以及billing对象下的first_name字段,但尝试的jq命令未能得到预期结果。
原始JSON示例(截断):
[ { "id": 727, "status": "processing", "total": "29.35", "billing": { "first_name": "John", "last_name": "Doe", ... } } ]
尝试的错误命令:
jq -r map({id,number,date_created,status,.billing[].first_name}) | (first | keys_unsorted) as $keys | map([to_entries[] | .value]) as $rows | $keys,$rows[] | @csv
问题分析
原命令存在两个关键问题:
billing是对象而非数组,不能用.billing[].first_name,且构造新对象时未给该字段命名,正确写法是first_name: .billing.first_name- 命令中包含了你不需要的
number、date_created字段,属于冗余内容
正确实现方法
1. 输出CSV格式(带表头)
如果需要将提取结果导出为CSV,使用以下命令:
jq -r ' map({id, status, total, first_name: .billing.first_name}) | (first | keys_unsorted) as $headers | map([.[]]) as $rows | $headers, $rows[] | @csv ' 你的文件名.json
2. 输出JSON格式
如果只需要提取后的JSON数组,命令更简洁:
jq 'map({id, status, total, first_name: .billing.first_name})' 你的文件名.json
内容的提问来源于stack exchange,提问作者user3190278
相关产品推荐
相关产品推荐

