json-order allows for conversion between JS Objects and a JSON string while keeping property order, controlled via a property map. All manner of nesting is supported.
To parse a JSON string and generate a map:
const result = orderedJson.parse(srcJson, prefix, separator);
srcJson
: a json stringprefix
[optional]: a non-emptystring
that controls what the key prefix value is in the generated map. Defaults to$
.separator
[optional]: a non-emptystring
that controls what the key separator is in the generated map. Defaults to~
.
result.object
will contain a JS object while result.map
will contain the generated property map.
To stringify a JS object maintaining a particular property order:
const jsonString = orderedJson.stringify(srcObj, map, 2);
srcObj
: an object with the properties in any ordermap
[optional]: the property map generated byparse
above. If the map is unset, the response is a standardJSON.stringify
.separator
[optional]: a non-emptystring
that controls what the key separator is in the generated map. Defaults to~
.space
[optional]: anumber
used to insert white space into the output JSON string for readability purposes, as per theJSON.stringify
documentation.
To duplicate a JS object but containing a particular property order:
const orderedObj = orderedJson.order(srcObj, map, 2);
srcObj
: an object with the properties in any ordermap
[optional]: the property map generated byparse
above. If the map is unset, the response is a standardJSON.stringify
.separator
[optional]: a non-emptystring
that controls what the key separator is in the generated map. Defaults to~
.
An object with a particular property order:
{
"z": {
"y": 5,
"b": [
false,
{
"d": 3,
"c": 2
},
14
]
},
"a": "hello"
}
Will generate a lookup object like:
{
"$": ["z", "a"],
"$.z": ["y", "b"],
"$.b.1": ["d", "c"]
}
JS Objects in JavaScript do keep their property insertion order (this behaviour is dependant on the JS engine), however this behaviour is not guaranteed by other systems you may interchange that object with.
For example, when storing a JS Object in a SQLite database, the returned object will have its properties in alphabetical order. Order in an array is preserved, however order of properties in an object is not.
This behavior is undesirable in certain cases. If a user has configured an application via JSON, they may choose to make logical groupings of properties. When this JSON is parsed to a JS Object, stored in the DB and extracted again, the groupings no longer exist because the properties have been alphabetically ordered.
There are several solutions to this problem, (eg. storing the data in a different format) but this migration process can be tedious and complex in certain use cases.
This particular implementation is in reference to the approach suggested for feature 1046 in Insomnia.
Please raise issues or feature requests via the Github issue tracker
Feel free to submit a pull request with your change!
yarn install
yarn test