如何使用 jq 按字段值对 json 对象流进行排序

如何使用 jq 按字段值对 json 对象流进行排序

我从如下所示的 json 开始:

{
  "object": "list",
  "data": [
    {
      "id": "in_1HW85aFGUwFHXzvl8wJbW7V7",
      "object": "invoice",
      "account_country": "US",
      "customer_name": "clientOne",
      "date": 1601244686,
      "livemode": true,
      "metadata": {},
      "paid": true,
      "status": "paid",
      "total": 49500
    },
    {
      "id": "in_1HJlIZFGUwFHXzvlWqhegRkf",
      "object": "invoice",
      "account_country": "US",
      "customer_name": "clientTwo",
      "date": 1598297143,
      "livemode": true,
      "metadata": {},
      "paid": true,
      "status": "paid",
      "total": 51000
    },
    {
      "id": "in_1HJkg5FGUwFHXzvlYp2uC63C",
      "object": "invoice",
      "account_country": "US",
      "customer_name": "clientThree",
      "date": 1598294757,
      "livemode": true,
      "metadata": {},
      "paid": true,
      "status": "paid",
      "total": 57000
    },
    {
      "id": "in_1H8B0pFGUwFHXzvlU6nrOm6I",
      "object": "invoice",
      "account_country": "US",
      "customer_name": "clientThree",
      "date": 1595536051,
      "livemode": true,
      "metadata": {},
      "paid": true,
      "status": "paid",
      "total":  20000
    }
  ],
  "has_more": true,
  "url": "/v1/invoices"
}

如果我做

cat sample.json | jq -C '.data[] | {invoice_id: .id, date: .date | strftime("%Y-%m-%d"), amount: .total} | .amount = "$" + (.amount/100|tostring)'

我可以成功地整理它(实际数据要冗长得多,需要消除数百行),这给了我:

{
  "invoice_id": "in_1HW85aFGUwFHXzvl8wJbW7V7",
  "date": "2020-09-27",
  "amount": "$495"
}
{
  "invoice_id": "in_1HJlIZFGUwFHXzvlWqhegRkf",
  "date": "2020-08-24",
  "amount": "$510"
}
{
  "invoice_id": "in_1HJkg5FGUwFHXzvlYp2uC63C",
  "date": "2020-08-24",
  "amount": "$570"
}
{
  "invoice_id": "in_1H8B0pFGUwFHXzvlU6nrOm6I",
  "date": "2020-07-23",
  "amount": "$200"
}

但这是错误的顺序。我想按日期字段排序,以便最新的项目显示在底部的最后。

我已经尝试过所有能想到的错误方法。我该如何申请sort_by(.date)这个?我不断收到cannot index string with string "date"错误(以及其他各种错误,但主要是那个错误)。

答案1

man jq

sort, sort_by(path_expression) 排序函数对其输入进行排序,输入必须是数组。

一般来说,并调用一个单独的jq命令时,您必须使用-s--slurp这将使这些顺序对象成为一个数组,然后您可以按键对其进行排序。

... | jq -s 'sort_by(.date)'

现在,如果您已经进行了选择并且希望该结果成为一个数组,那么我想用括号将其全部括起来将使其:

jq '[ <some_existing_selection> ] | sort_by(.date)' file.json

例子

对于您开始的 json,假设最初您正在执行类似的操作(生成一系列对象):

jq '.data[] | {id: .id, date: .date}' file.json

你必须将整个 jq 选择括在括号中以使其成为一个数组:

jq '[.data[] | {id: .id, date: .date}]' file.json

现在可以对这个数组进行排序:

jq '[.data[] | {id: .id, date: .date}] | sort_by(.date)' file.json

答案2

示例 JSON:

{"first_name":"Savannah","last_name":"Williams"}
{"first_name":"Aria","last_name":"Acevedo"}
{"first_name":"Emma","last_name":"Puckett"}
{"first_name":"Claire","last_name":"Mathis"}
{"first_name":"Ryder","last_name":"Wong"}

按字段排序:

cat sample.json | jq -s -c 'sort_by(.first_name) | .[]'

我从这里得到的:

来源网站

相关内容