我从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"
错误(以及其他各种各样的错误,但大多是那个错误)。
发布于 2020-10-09 23:00:40
来自man jq
排序,sort_by(path_expression)排序函数对其输入进行排序,这必须是一个数组。
通常,在调用单独的jq
命令时,必须使用-s
,--slurp
,这将使这些顺序对象成为数组,然后可以按键对其进行排序。
... | jq -s 'sort_by(.date)'
现在,如果您已经有了一个选择,并且希望这个结果是一个数组,那么我想用方括号将其全部包装起来就可以了:
jq '[ ] | 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
发布于 2023-05-29 09:28:19
示例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) | .[]'
我从这里得到的:
https://unix.stackexchange.com/questions/613779
复制相似问题