From 540715b36e8569fa359161cc1fb508d377a65794 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 29 Nov 2026 04:25:08 +0800 Subject: [PATCH] fix(json): preserve lexical order in typed encoding Cargo feature unification can enable serde_json preserve_order and expose the typed encoder's map iteration order. Sort object keys recursively just before serialization, leaving array order unchanged. Cover nested typed objects and arrays with an exact-output regression. --- src/builtins/runtime/logical_json.rs | 4 +++- tests/map_json_behavior_tests.rs | 18 ++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/src/builtins/runtime/logical_json.rs b/src/builtins/runtime/logical_json.rs index 7d9815a5..f9df1145 100644 --- a/src/builtins/runtime/logical_json.rs +++ b/src/builtins/runtime/logical_json.rs @@ -35,7 +35,9 @@ pub(super) fn encode_typed( ) -> VmResult { let schema = prepare_json_schema(descriptor, &names)?; charge_value(value, &mut 0)?; - let json = encode_value(value, &schema, Position::Value, 0, &names)?; + let mut json = encode_value(value, &schema, Position::Value, 0, &names)?; + // Keep lexical key order even if a downstream crate enables preserve_order. + json.sort_all_objects(); serde_json::to_string(&json) .map_err(|err| VmError::HostError(format!("typed json encode: {err}"))) } diff --git a/tests/map_json_behavior_tests.rs b/tests/map_json_behavior_tests.rs index c292e3cb..d03b2097 100644 --- a/tests/map_json_behavior_tests.rs +++ b/tests/map_json_behavior_tests.rs @@ -572,6 +572,24 @@ fn unit_scalar_array_and_map_round_trip() { assert_eq!(reload_eval(source), Value::Bool(true)); } +#[test] +fn typed_json_encode_sorts_nested_object_keys() { + let source = r#" + use json; + struct Payload { stats: [map], label: string } + let mut values: map = {}; + values["z"] = 1; + values["a"] = 2; + values["m"] = 3; + let value: Payload = {stats: [values, {}], label: "public"}; + json::encode(value); + "#; + assert_eq!( + eval(source), + Value::string(r#"{"label":"public","stats":[{"a":2,"m":3,"z":1},{}]}"#), + ); +} + #[test] fn option_unit_field_none_omits_and_some_encodes_null() { let source = r#"