I have the following JSON structure that comes from a web request and I need to parse it and preserve the order of the keys.
const json = `{
"2": "first",
"1": "second"
}`;
However as per spec, JSON.parse()
does not guarantee the order of the keys and in nearly all implementations this means that the keys are ordered alphabetically or numerically, resulting in the following object.
{
1: "second"
2: "first"
}
To preserve the order of the keys, I wanted to directly parse the JSON string into a Map, because the Map will preserver the order of the keys. However everything I found so far, suggest using the following code which will obviously first parse it into an object (and destroy the order of the keys) and then convert that object into a Map.
new Map(Object.entries(JSON.parse(json)));
So my question is if there is a way to directly parse the JSON into a map and preserve the order of the keys.
The second question would be if that is also possible only for a sub-object, like this
const nestedJson = '{
"I_dont_care_about_the_order": "foobar",
"Preserve_the_order_in_this_object": {
"2": "first",
"1": "second"
}
}';