jawk/functions/object/sort_objects/
sort_by_keys.rs

1use std::rc::Rc;
2
3use crate::{
4    functions_definitions::{Arguments, Example, FunctionDefinitions},
5    json_value::JsonValue,
6    processor::Context,
7    selection::Get,
8};
9
10pub fn get() -> FunctionDefinitions {
11    FunctionDefinitions::new("sort_by_keys", 1, 1, |args| {
12        struct Impl(Vec<Rc<dyn Get>>);
13        impl Get for Impl {
14            fn get(&self, value: &Context) -> Option<JsonValue> {
15                match self.0.apply(value, 0) {
16                    Some(JsonValue::Object(map)) => {
17                        let mut map = map.clone();
18                        map.sort_keys();
19
20                        Some(map.into())
21                    }
22                    _ => None,
23                }
24            }
25        }
26        Rc::new(Impl(args))
27    })
28    .add_alias("order_by_keys")
29    .add_description_line("Sort an object by it's keys.")
30    .add_description_line("If the first argument is an object, return object sorted by it's keys.")
31    .add_example(
32        Example::new()
33            .add_argument("{\"z\": 1, \"x\": 2, \"w\": null}")
34            .expected_output("{\"w\":null,\"x\":2,\"z\":1}"),
35    )
36    .add_example(Example::new().add_argument("false"))
37}