Apologies if this has been documented elsewhere, I had a look around and couldn’t find anything.
When using JSON::Serializable
and to_json
to turn objects into JSON, particularly classes and structs, I’ve noticed that the keys of the output are always sorted alphanumerically, rather than according to their order in the original object.
For example this:
struct PagedResponse(U)
include JSON::Serializable
property page : Int64
@count : Int64
@[JSON::Field(emit_null: true)]
@previous : String?
@[JSON::Field(key: "next", emit_null: true)]
@next_page : String?
@[JSON::Field(emit_null: true)]
@results : Array(U)
end
turns out like this, with alpha-sorted keys:
{
"count": 95,
"next": "https://127.0.0.1:8080/attributes/?page=2",
"page": 1,
"previous": null,
"results": [ //omitted ]
}
It’s not a big deal, but for APIs it’s nice to be able to guarantee the order, especially if you end up with a large array like results
there having some other keys after it, making it look messier for other humans reading it.
Is there a way I can get around this and guarantee output ordering?