How to sort a json file by keys and values of those keys in jq

We're building a website using the Pentaho CTools library, which has a graphical dashboard editor which writes out JSON-format files for part of the dashboard.

I'd like to apply a transform to these files before check-in to git in order to sort them by key and then by the value of certain keys. The purpose is to make diffs easier, since the editor has a habit of rearranging all of the json fields.

For example, we might have something like this:

{
"components": {
"rows": [
{
"id": "CHARTS",
"name": "Charts",
"parent": "UnIqEiD",
"properties": [
{
"name": "Group",
"type": "Label",
"value": "Charts"
}
],
"type": "Label",
"typeDesc": "<i>Group</i>"
},
{
"id": "kjalajsdjf",
"meta_cdwSupport": "true",
"parent": "CHARTS",
"properties": [
{
"name": "name",
"type": "Id",
"value": "Value1"
},
{
"name": "title",
"type": "String",
"value": "Value2"
},
{
"name": "listeners",
"type": "Listeners",
"value": "[]"
},
...

We are able to jq --sort-keys (http://stedolan.github.io/jq/) to sort all of the keys, but I'm struggling to find out how to use the sort_by function to then sort certain specific elements by the value of certain keys (so, in the example above, sorting by properties.name for example. Any ideas?

104911 次浏览

在 IRC 频道的帮助下,我找到了答案。

基本上,它看起来像这样:

jq \
'.components.rows|=sort_by(.id)|.components.rows[].properties|=sort_by(.name)' \
file.json > out.json

选择正确的对象,
如果需要,可以进入数组,
然后 sort_by一个单一的值。

我正在尝试 sort_by(.components.rows.id),但是失败了。

|=而不是 |传递这些值,而不是剥离它们。

这没有回答这个问题,但是这里有另一种按属性/键排序的方法:

jq --sort-keys . my_file > sorted_file

-or-

jq -S . my_file > sorted_file