json icon indicating copy to clipboard operation
json copied to clipboard

Missing documentation with regards to sorted output

Open bcc32 opened this issue 2 years ago • 2 comments

I found this behavior surprising: for a Serializable value t, the following prints a JSON object with all keys sorted lexicographically:

serde_json::to_writer_pretty(std::io::stdout(), &serde_json::to_value(t)?)?;

On the other hand, the following prints the same value without sorting:

serde_json::to_writer_pretty(std::io::stdout(), t)?;

Of course, if you know how the underlying implementation works, this isn't actually that surprising, but I didn't actually see anywhere where this difference was documented, nor does the documentation of Value mention that it does have the sorting behavior.

bcc32 avatar Apr 22 '23 04:04 bcc32

I had assumed it's a non-goal for serde-json to preserve order of maps. As long as preserve_order is not enabled, the user shouldn't rely on any particular ordering or sorting behavior

kangalio avatar May 23 '23 17:05 kangalio

One might reasonably want "pretty printing" of JSON to include sorting keys, or at least some other way of producing a "canonical" JSON document (for determinism, etc.). I suppose the underlying motivation for my request is similar to #1014.

In any case, for purposes of this issue, I would be happy if serde-json at least explicitly disclaimed any particular sorting behavior where relevant.

bcc32 avatar May 24 '23 04:05 bcc32