如何根据给定的密钥在shell脚本中对json文件进行排序?

时间:2015-06-23 15:12:37

标签: json shell sorting unix sh

我想根据shell脚本(.sh)文件中的密钥(票价)对包含json数据的文件进行排序。有没有办法实现相同的目标?

{ "route":[
   {"match":"true","column":"10","fare":"120.0","source":"false","length":"1","name":"41","row":"4","width":"1","zIndex":"0"},
   {"match":"true","column":"9","fare":"110.0","source":"false","length":"1","name":"37","row":"3","width":"1","zIndex":"0"},
   {"match":"true","column":"8","fare":"500.0","source":"false","length":"1","name":"33","row":"2","width":"1","zIndex":"0"},
   {"match":"true","column":"7","fare":"510.0","source":"false","length":"1","name":"29","row":"1","width":"1","zIndex":"0"},
   {"match":"true","column":"6","fare":"50.0","source":"false","length":"1","name":"29","row":"0","width":"1","zIndex":"0"}
   ]
};

1 个答案:

答案 0 :(得分:1)

;
jq '.route = (.route | sort_by(.fare))' file.json

请注意,排序是词汇(“50”位于中间)。这是因为值是字符串而不是数字。要获得数字排序,我们需要转换为数字

{
  "route": [
    {
      "zIndex": "0",
      "match": "true",
      "column": "9",
      "fare": "110.0",
      "source": "false",
      "length": "1",
      "name": "37",
      "row": "3",
      "width": "1"
    },
    {
      "zIndex": "0",
      "match": "true",
      "column": "10",
      "fare": "120.0",
      "source": "false",
      "length": "1",
      "name": "41",
      "row": "4",
      "width": "1"
    },
    {
      "zIndex": "0",
      "match": "true",
      "column": "6",
      "fare": "50.0",
      "source": "false",
      "length": "1",
      "name": "29",
      "row": "0",
      "width": "1"
    },
    {
      "zIndex": "0",
      "match": "true",
      "column": "8",
      "fare": "500.0",
      "source": "false",
      "length": "1",
      "name": "33",
      "row": "2",
      "width": "1"
    },
    {
      "zIndex": "0",
      "match": "true",
      "column": "7",
      "fare": "510.0",
      "source": "false",
      "length": "1",
      "name": "29",
      "row": "1",
      "width": "1"
    }
  ]
}
jq '.route = (.route | sort_by(.fare | tonumber))' file.json