0

I'm constructing a JSON based on certain values,

my code is as follows,

var txt = '{ \"' + 9837 + '\": "Cost-A", \"' + 8943 + '\": "Cost-B", \"' + 13917 + '\": "Cost-C", \"' + 13917 + '\": "Cost-D"}'; _obj = JSON.parse(txt); 

The output I get in the console is,

Object {9837: "Cost-A", 8943: "Cost-B", 13917: "Cost-D"} 

Cost-C has been skipped completely? or is there something trivial I'm missing? How can I solve this?

3
  • Why are you constructing JSON with strings in JavaScript? Commented May 9, 2013 at 6:01
  • 13917 is duplicate key in your stringified JSON. So it is taking only latest one. Commented May 9, 2013 at 6:03
  • @elclanrs Well, there's a lot of mapping that's happening as well, which is beyond the scope of this question, is there an alternative way? Commented May 9, 2013 at 6:03

1 Answer 1

2

Javascript ojects cannot have duplicate keys. Hence it gets overwritten.

{ "9837": "Cost-A", "8943": "Cost-B", "13917": "Cost-C", "13917": "Cost-D"}

The parser would add the latest value of the key.

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

2 Comments

You cannot use double quotes inside double quotes, until you escape them.
@badZoke , No, that would be a badJoke on the way a javascript object works. What would you expect your object to return if you do myObj['13917']

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.