Indie game storeFree gamesFun gamesHorror games
Game developmentAssetsComics
SalesBundles
Jobs
Tags

Support for preserving JSON key order?

A topic by murzy created Apr 11, 2021 Views: 203 Replies: 2
Viewing posts 1 to 3
(1 edit)

Hi!

Any chance of fixing a regression bug where JSON keys are no longer kept in the order they were defined in the object when you look at the output of tj_encode()?

The older version of the library (1.0.4?) worked fine, but we updated to the latest version (1.0.6) with GMS 2.3 support and it was disappointing to see the issues caused by the internal usage of  GMS function variable_struct_get_names which doesn't seem to guarantee the order of keys.

Example:

var obj1 = tj_object(
    "a", 1,
    "b", 2,
    "c", 3,
    "d", 4,
    "e", 5,
);
var json1 = tj_encode(obj1, "    ");     
show_debug_message(json1);
var obj2 = tj_decode(json1);     
var json2 = tj_encode(obj2, "    ");     
show_debug_message(json2);
var obj3 = tj_decode(json2);     
var json3 = tj_encode(obj3, "    ");     
show_debug_message(json3);

Prints:

{     
    "d": 4,     
    "e": 5,     
    "c": 3,     
    "b": 2,     
    "a": 1 
} 
{     
    "a": 1,     
    "e": 5,     
    "c": 3,    
    "b": 2,     
    "d": 4 
} 
{     
    "d": 4,     
    "e": 5,     
    "c": 3,     
    "b": 2,     
    "a": 1 
}

Note the alternating order of keys.

We were using this library for an editor for our game, and this is devastating for git diff logs as you can imagine.

Would it be easy to implement something that guarantees the key order? Any ideas for a workaround? Perhaps sort the keys when encoding?


PS. The library has been a real lifesaver in pre GMS 2.3 times. Many thanks!

Managed to fix this on my own by adding a layer of abstraction into every place the structs are handled like this:

{ value: {}, order: {} }

And then when tj_encode is called, the order information is used for sorting when writing stuff.


Would be nice to have official support for this, though!

Developer (1 edit)

I believe that you are the second person to ask about this, but I cannot think of a way to handle this without rewriting the extension for the third time - at most I can add an option to alphabetically order fields and/or a special field that you can set to an array of keys to control field output order, so something like

{ "a": 1, "c": 3, "b": 2, "$$order$$": ["a", "b", "c"] }