Home > front end >  How to sort JSON in rust?
How to sort JSON in rust?

Time:03-12

Is it possible to sort JSON in rust language? If it is possible then how?

Like this one:


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);

CodePudding user response:

More or less the same code in 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}");
}

Plaground link

As @cdhowie pointed out, Rust gives you the option to sort items by key instead of sorting keys only and then performing a lookup each time:

    let hmac_payload = headers
        .iter()
        .sorted_by_key(|item| item.0)
        .map(|item| format!("{}:{}", item.0, item.1))
        .join("\n");

As @Caesar pointed out, using BTreeMap instead of HashMap would be a more efficient solution since it stores items sorted by their keys, thus you won't need to sort items at all.

  • Related