You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从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

问题分析

原命令存在两个关键问题:

  1. billing是对象而非数组,不能用.billing[].first_name,且构造新对象时未给该字段命名,正确写法是first_name: .billing.first_name
  2. 命令中包含了你不需要的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 15:15:28