syrupy icon indicating copy to clipboard operation
syrupy copied to clipboard

Ordering JSON keys of Python dictionary snapshots

Open willgdjones opened this issue 1 year ago • 5 comments

Thanks for the great library!

We'd like to order the JSON keys alphabetically by information in the value, not just by the key. We are using the JSONSnapshotExtension. The reason is that we'd like to preserve sensible diffs in version control even if the names of the keys change, since the reordering appears as large deletions and additions of code.

For example, we'd like to make sure the snapshotted JSON is sorted by the value of the "Type" (first a, then b) etc...

{
  'b': {
    {
      "Type": "a",
      "Data": "X"
    },
  'a': {
    {
      "Type": "b",
      "Data": "Y"
    }
}

Not obvious how to do this because Python dictionaries are unordered, and using OrderedDict doesn't seem to preserve order.

Thanks!

willgdjones avatar Aug 18 '22 13:08 willgdjones

It looks like we don't treat OrderedDicts any differently from regular dicts. Arguably we should do an instanceof OrderedDict check and if it's ordered, preserve the original key order rather than apply our key sort: https://github.com/tophat/syrupy/blob/1d3ae5779e1a19f998895f3812187e0ddc57fd79/src/syrupy/extensions/amber/serializer.py#L172

This would be a breaking change though but I think it makes sense.

noahnu avatar Aug 18 '22 13:08 noahnu

Makes sense! In the meantime, we have converted the dictionary to a list of key, value pairs, which seems to work ok. It would be cleaner to have it as JSON dictionary key, values but the workaround is ok for the time being.

Thanks for the help!

willgdjones avatar Aug 18 '22 13:08 willgdjones

Why would it be a breaking change?

willgdjones avatar Aug 18 '22 13:08 willgdjones

This could be something that I can take a look at contributing too

willgdjones avatar Aug 18 '22 13:08 willgdjones

It'd be a breaking change to change the default snapshot behaviour because folks would have to run --snapshot-update to adopt the latest version of syrupy.

That being said, a non-breaking approach would be to extend the data serializer class or add a feature for custom key ordering.

noahnu avatar Aug 18 '22 13:08 noahnu