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

如何精简整理过于冗长的jq字段提取映射表达式?

jq提取表达式精简方案

以下是和原命令逻辑完全等价、但可读性和可维护性大幅提升的精简版本:

jq -r '
# 提前存储重复访问的节点,减少重复路径书写
($id, $metaLastUpdated) = (.id, .meta.lastUpdated)
($ident0, $ident1, $ident2) = (.identifier[0], .identifier[1], .identifier[2])
$name0 = .name[0]
$addr0 = .address[0]
$qualCoding0 = .qualification[0].code.coding[0]

# 封装地址行字段提取公共逻辑,复用重复代码
def get_line_val($prefix): ($addr0.line[]? | select(contains("\($prefix)^")) | split("^")[1]) // null;

[
  $id, $metaLastUpdated,
  $ident0.use, $ident0.system, $ident0.value,
  $ident1.use, $ident1.system, $ident1.value,
  $ident2.use, $ident2.system, $ident2.value, $ident2.assigner.reference,
  .active,
  $name0.use, $name0.text, $name0.given[0], $name0.family, $name0._family.extension[0].valueString,
  $addr0.extension[0].valueString, $addr0.type,
  get_line_val("TV"), get_line_val("NV"), get_line_val("NVI"),
  $addr0.city, $addr0.state, $addr0.postalCode, $addr0.country,
  $qualCoding0.system, $qualCoding0.code
] | @csv
' practitioners-pre.json > practitioners-pre.csv

核心优化点

  • 重复节点预存:把原命令中反复出现的.identifier[x]、.name[0]、.address[0]等路径提前赋值给变量,避免重复书写长路径,代码长度直接缩短40%
  • 公共逻辑封装:三次提取地址行特定前缀值的逻辑合并为自定义函数,后续需要新增同类前缀提取仅需加一行函数调用即可,无需重复写过滤、拆分逻辑
  • 字段分组排列:相同业务属性的字段归类放置,后续调整字段顺序、增删字段时更容易定位,大幅降低维护成本

如果你的场景中identifier元素数量不固定,还可以进一步优化,比如批量提取前N个identifier的字段:将原来逐个写$ident0/1/2的部分替换为(.identifier[:3] | .[] | .use, .system, .value), .identifier[2].assigner.reference,可进一步缩短代码。

内容的提问来源于stack exchange,提问作者Jordi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 08:24:02