2

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?

3
  • 2
    No. JavaScript objects are not ordered. Commented Aug 13, 2013 at 13:15
  • yes just use alphanumeric syntax for key. like k_28 so the order will not change. Commented Aug 13, 2013 at 13:16
  • Pass the products as arrays instead of objects. Commented Aug 13, 2013 at 13:16

1 Answer 1

3

You need to make use of Arrays to preserve the formatting.

Sign up to request clarification or add additional context in comments.

1 Comment

Right. My bad. I ended up using JSON formatted like this: {"products":[[25,"productName"],...],"excludedProducts":[[83,"productName"],...]}

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.