Reputation: 2479
I have a JSON string like below:
{"2":"News 2","7":"News 7","4":"Recipe 4","6":"Recipe 6"}
The numbers are references and the order is important.
When I use JSON.parse, it assumes that the numerals are indexes instead of key strings regardless of the quotation marks.
How can I successfully convert this string to an object while retaining the proper order of the items?
Much thanks for any help.
Upvotes: 1
Views: 330
Reputation: 4340
I am surprised there isn't a flag that says "preserve strings" (similar to JSON_NUMERIC_CHECK
in PHP). Mad that a "2" gets converted to a 2.
One possible solution is to add an 'a' at the start of the key - this forces string conversion but you just need to strip it off in your javascript. The following will work:
{"a2":"News 2","a7":"News 7","a4":"Recipe 4","a6":"Recipe 6"}
Upvotes: 0
Reputation: 2396
Despite needing to appear in a specific order in the document due to json syntax, the order of keys in a javascript object is undefined. Implementation details between JS engines and versions can change how order of object keys works. When order matters, you should use an array.
There are many shapes you could choose for your collection to represent this order-of-keys, but I would arrange it like this:
{
elements: {"2":"News 2","7":"News 7","4":"Recipe 4","6":"Recipe 6"},
elementOrder: ["2", "7", "4", "6"]
}
As for the keys being turned into numbers, this is not really an issue as long as you're using an array for order. You can access the resulting object via numbers or strings and it will work either way.
elements[2]
elements["2"] // both return "News 2"
Upvotes: 1
Reputation: 2105
You should transform this to JSONArray
of JSONObject
s.
When using array, the order is preserved.
Example:
[ {"2": "News 2"} , {"7": "News 7"}, {"4": "Recipe 4"}, {"6": "Recipe 6"} ]
However, this is not the appropriate way to represent data in JSON, instead, you should do something like this:
[{"id":"2","name":"News 2"}, {"id":"7","name":"News 7"},{"id":"4","name":"News 4"},{"id":"6","name":"News 6"}]
Upvotes: 0