Order of fields in serde_json::to_string()

My code produces trace records using json!() and serde_json::to_string(). I'd like the values to appear in the string in the order specified in the macro, but they are alphabetized. For example,

json!({"foo": 1, "bar": 2})

results in

{"bar":1, "foo":2}

That's not a problem for this simple example, but it is when "bar" is a big struct. Is there a way I can get the order specified in the macro?

It looks like there's a serde_json feature preserve_order that might do that? In general, JSON objects have intentionally unordered elements.

1 Like

Note also that derived implementations of Serialize respect struct field order. Maybe what you really want is a new struct type that you can serialize, instead of the loosely-typed json!() macro?

2 Likes

I do have a struct type for the trace record header. However, each trace record format has a unique body, and I've got dozens of formats. I started out creating a struct for each one, but having all those one off structs quickly got out of hand. @asymmetrikon's suggestion to use preserve_order does exactly what I want far more easily.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.