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

如何用jq按componentIndex排序JSON并提取color值?

解决JSON对象按componentIndex排序并提取color的问题

你的问题出在没有正确将JSON对象转换为可排序的数组结构。原JSON是一个顶层对象,直接用-s参数只会把整个对象包裹成单元素数组,sort_by(.[].componentIndex)无法对单个元素排序,所以结果和原文件一致。

正确步骤与命令

1. 仅提取排序后的color值列表

如果只需要按componentIndex升序排列的color值,执行以下命令:

jq 'to_entries | sort_by(.value.componentIndex) | map(.value.color)' in.json > out.json

2. 生成按componentIndex排序后的完整JSON对象

如果需要保留原键值对结构并按componentIndex排序,执行以下命令:

jq 'to_entries | sort_by(.value.componentIndex) | map({(.key): .value}) | add' in.json > sorted_object.json

关键逻辑说明

  • to_entries:将顶层JSON对象转换为键值对数组(形如[{"key": "xxx", "value": {...}}, ...]),这是实现对象排序的核心前提——因为原生JSON对象本身无固定顺序,必须转为数组才能进行排序操作。
  • sort_by(.value.componentIndex):针对数组中每个元素的value.componentIndex字段执行升序排序。
  • map(.value.color):遍历排序后的数组,提取每个元素中的color值。
  • map({(.key): .value}) | add:将排序后的键值对数组重新组合为JSON对象。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 11:20:08