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

如何依据input.json的键顺序对output.json进行排序?

如何用jq按input.json的键顺序排序output.json?

我用翻译管理工具处理多语言文件时遇到个问题:上传input.json后,译者完成翻译导出的output.json键和原文件完全一致,但键的顺序被打乱了。在Pull Request里对比新旧文件时,键顺序差异会产生大量无效diff,增加评审难度。我知道可以用jq按字母序排序两者,但能不能直接复用input.json的键顺序来重新排列output.json?

演示数据

input.json

{
  "BathroomType": "Type of bathroom",
  "BuildingType": "Type of building",
  "enums": {
    "OrientationGarden": {
      "EAST": "East",
      "SOUTH": "South",
      "NORTH": "North",
      "WEST": "West"
    },
    "TerrainRecentDestination": {
      "EXTRACTION": "extraction",
      "PARK": "park"
    }
  }
}

output.json

{
  "BathroomType": "Type of bathroom2",
  "enums": {
    "TerrainRecentDestination": {
      "EXTRACTION": "extraction",
      "PARK": "park"
    },
    "OrientationGarden": {
      "SOUTH": "South",
      "EAST": "East2",
      "NORTH": "North",
      "WEST": "West"
    }
  },
  "BuildingType": "Type of building"
}

解决方案

可以用jq提取input.json的键路径顺序,然后按这个顺序重构output.json,命令如下:

jq --argfile input input.json '($input | paths(scalars) | map(select(type=="string"))) as $paths | reduce $paths[] as $p (.; setpath($p; getpath($p)))' output.json > sorted_output.json

命令解释

  1. ($input | paths(scalars) | map(select(type=="string"))):提取input.json中所有标量值的键路径(比如["BathroomType"]、["enums", "OrientationGarden", "EAST"]),确保只保留字符串类型的键,避免处理数组索引(如果有的话)。
  2. reduce $paths[] as $p (.; setpath($p; getpath($p))):遍历提取到的路径数组,按顺序从output.json中取出对应路径的值,重新构建新的JSON对象,完全复用input.json的键层级和顺序。

执行结果

生成的sorted_output.json会和input.json的键顺序完全一致,同时保留output.json的译文内容:

{
  "BathroomType": "Type of bathroom2",
  "BuildingType": "Type of building",
  "enums": {
    "OrientationGarden": {
      "EAST": "East2",
      "SOUTH": "South",
      "NORTH": "North",
      "WEST": "West"
    },
    "TerrainRecentDestination": {
      "EXTRACTION": "extraction",
      "PARK": "park"
    }
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 13:27:09