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

如何使用jq按自定义非字母顺序对JSON数组进行排序?

按自定义非字母顺序排序JSON数组的解决方法

你的问题核心是利用jq的index()函数获取元素在自定义顺序数组中的位置,以此作为排序依据。之前的命令写法有误,正确的实现方式如下:

正确的jq命令

jq --argjson order '["dog", "bird", "cat"]' 'sort_by($order | index(.entityType))' data.json

命令解释

  • --argjson order '["dog", "bird", "cat"]':将自定义排序顺序以JSON数组形式传入jq,作为变量$order
  • sort_by($order | index(.entityType)):对数组中的每个对象,先通过$order | index(.entityType)获取其entityType在自定义顺序数组中的索引位置,再根据该索引值排序,从而实现自定义顺序的排序效果

执行结果

运行上述命令后,data.json中的数据会按照dog→bird→cat的顺序返回:

[
  { "id": 2, "entityType": "dog" },
  { "id": 3, "entityType": "bird" },
  { "id": 1, "entityType": "cat" },
  { "id": 4, "entityType": "cat" }
]

扩展:处理未定义的entityType值

如果数据中存在不在自定义顺序里的entityType,可以添加默认逻辑将这类元素排在最后:

jq --argjson order '["dog", "bird", "cat"]' 'sort_by($order | index(.entityType) // length)' data.json

这里的// length表示当index()返回null(元素不在自定义顺序中)时,用数组长度作为索引,让这类元素排在所有指定顺序元素之后。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 16:48:12