是否可以用 rust 語言對 JSON 進行排序?如果有可能那怎么辦?
像這個:
const headers = {
'checkout-account': '1234',
'checkout-algorithm': 'sha256',
'checkout-method': 'POST',
'checkout-nonce': '564635208570151',
'checkout-timestamp': '2018-07-06T10:01:31.904Z',
};
const calculateHmac = (body=false, params) => {
const hmacPayload = Object.keys(params)
.sort()
.map((key) => [key, params[key]].join(':'))
.concat(body ? JSON.stringify(body) : '')
.join('\n');
};
calculateHmac(false, headers);
uj5u.com熱心網友回復:
Rust 中或多或少相同的代碼:
use itertools::Itertools;
use std::collections::HashMap;
fn main() {
let headers = HashMap::from([
("checkout-account", "1234"),
("checkout-algorithm", "sha256"),
("checkout-method", "POST"),
("checkout-nonce", "564635208570151"),
("checkout-timestamp", "2018-07-06T10,01,31.904Z"),
]);
let hmac_payload = headers
.keys()
.sorted()
.map(|key| format!("{}:{}", key, headers[key]))
.join("\n");
println!("{hmac_payload}");
}
游樂場鏈接
正如@cdhowie 指出的那樣,Rust 為您提供了按鍵對專案進行排序的選項,而不是僅對鍵進行排序,然后每次都執行查找:
let hmac_payload = headers
.iter()
.sorted_by_key(|item| item.0)
.map(|item| format!("{}:{}", item.0, item.1))
.join("\n");
正如@Caesar 指出的那樣,使用BTreeMap代替HashMap將是一個更有效的解決方案,因為它存盤按其鍵排序的專案,因此您根本不需要對專案進行排序。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/442693.html
