0

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"   
    }   
}';
wertzui
  • 5,148
  • 3
  • 31
  • 51
  • 1
    Your "JSON" is not JSON. Its syntax is invalid, as is your desired output object – CertainPerformance Apr 13 '21 at 07:09
  • 1
    Why do you care about the order? If the order is relevant the sender should send an array instead. – luk2302 Apr 13 '21 at 07:10
  • Sorry, the JSON was incorrect, I fixed it. I care about the order because the entries in that object are coming from a web request and ordering is happening on the server. The server is using the object IDs (integers) as keys in the returned object, but send them in the correct order in the JSON string. – wertzui Apr 13 '21 at 07:19
  • 1
    Then the chosen data format for handling, sending and retrieving data needs to be fixed at server-side. If FE-logic starts fixing data-exchange formats, something already is utterly wrong with the handling of such data in/at the middleware/backend. – Peter Seliger Apr 13 '21 at 18:41

1 Answers1

0

You can not change the order of the keys who are like 32 bit integer indices of an array. Javascript move them in order to top.

But you could take an object as value and add a property of the wanted order, like

json = '{
    "2": { "order": 1, "value": "first" },
    "1": { "order": 2, "value": "second" }
}';
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392