Json out in table field order

Hi ,
We have api in golang . where customer want json should be as in table filed order .

Which we have tried in golang . it is not possible.

we want to migrate same api in rust to solve that issue.

Please guide us it is possible.

Example : table : emp
. empcode,empname,age,desg,sal,add

json should be in same order
{
empocde:,
empname: ,
age : 10,
desg: ,
sal : ,
add :
}

JSON objects are unordered by specification, so probably no implementation will guarantee that.

3 Likes

serde_json has a preserve_order feature that will preserve insertion order for values constructed manually.

It won't necessarily automatically make all of the serde_json API do what you want though, you may have to do some things manually.

preserve_order feature replace hashmaps in serde_json::Value enum with indexmap. You should not use this enum if you know the structure of the JSON.

Practically JSON string produces by serde_json from #[derive(Serialize)] struct reflects the ordering of the struct declaration itself. I'm not sure it's guaranteed but it's pretty stable. You can add some test yourself for extra safety.

https://serde.rs/derive.html

1 Like