JSON.sortify icon indicating copy to clipboard operation
JSON.sortify copied to clipboard

Possible to specify order of properties?

Open ThomasDotCodes opened this issue 8 years ago • 3 comments

Let's say I have the following JSON object:

{ "name" : "John", "age" : 55, "sex" : "M" }

using sortify, of course it will sort them by alphabetical order. However, what if I always wanted the JSON to be exported in the format as above? Is there a way to pass in similar to a whitelist--but have the whitelist retain the order as I enter it?

For example to replicate structure above, the call would be:

JSON.sortify(data, ['name', 'age', 'sex']);

ThomasDotCodes avatar Sep 12 '16 18:09 ThomasDotCodes

We'd have to use another API though, because an array would imply that only those properties are kept.

mk-pmb avatar Jan 05 '17 22:01 mk-pmb

Right. JSON.sortify was built to provide maximal compatibility with JSON.stringify. Providing a custom order as suggested by @producerism would break that.

We could introduce a fourth parameter though: JSON.sortify(obj, replacer, space, customOrderHere)

In order to retain JSON.sortify.length === 3, we must access this using arguments[3] rather than a named parameter.

ThomasR avatar Jan 13 '17 19:01 ThomasR

I implemented the abovementioned in branch/customSorting. Please check if that fits your needs.

ThomasR avatar Jan 13 '17 21:01 ThomasR