I have a string like this one:
{
"products":{"56":"productName","28":"productName"},
"excludedProducts":{"83":"productName","1":"poductName"}
}
So what I want is to get an object in javascript which looks like this:
{
products: {
"56": "productName",
"28": "productName"
},
excludedProducts: {
"83": "productName",
"1": "productName"
}
}
But JSON.parse() converts numbers into indexes and I get
{
products: {
28: "productName",
56: "productName"
},
excludedProducts: {
83: "productName",
1: "productName"
}
}
So basically, is there a way to preserve order of elements after parsing the string formatted like that?
asked Aug 13, 2013 at 13:14
wazelin
7611 gold badge11 silver badges23 bronze badges
-
2No. JavaScript objects are not ordered.JJJ– JJJ2013年08月13日 13:15:18 +00:00Commented Aug 13, 2013 at 13:15
-
yes just use alphanumeric syntax for key. like k_28 so the order will not change.developerCK– developerCK2013年08月13日 13:16:04 +00:00Commented Aug 13, 2013 at 13:16
-
Pass the products as arrays instead of objects.jbabey– jbabey2013年08月13日 13:16:25 +00:00Commented Aug 13, 2013 at 13:16
1 Answer 1
You need to make use of Arrays to preserve the formatting.
answered Aug 13, 2013 at 13:15
Shankar Narayana Damodaran
68.6k43 gold badges102 silver badges129 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
wazelin
Right. My bad. I ended up using JSON formatted like this: {"products":[[25,"productName"],...],"excludedProducts":[[83,"productName"],...]}
lang-js