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"
錯誤(以及其他其他錯誤,但主要是那個錯誤)。
從
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