1

I want to add string with special character in JSON as KEY.For example "Sam@123"
Here is the code, that I am trying.

<script type="text/javascript">

var jsonObj={"sam":1,"rudolph":1,"js":1," ":12};
var key="samw@123";
alert("Add it.")
// Adding the key with Special Character in JSON
eval("jsonObj."+key+"=11")
alert("Added successfully.")

for(var i=0; i< Object.keys(jsonObj).length; i++){
alert("KEY#"+Object.keys(jsonObj)[i]);
}

</script>

I am getting following error at line 6 "eval......".

Uncaught SyntaxError: Unexpected token ILLEGAL

Is there any other way to add special character in Json as KEY?

I am also not able to add

var key="samw-123";

for this I am getting error saying

Uncaught ReferenceError: Invalid left-hand side in assignment

Ashish Agarwal
  • 6,215
  • 12
  • 58
  • 91
  • 1
    you don't need to use eval to do this, see wizard's answer below – wong2 Oct 23 '11 at 12:20
  • 1
    (a) You are not working with JSON here, only with JavaScript objects. (b) possible duplicate of [Dynamic object property name](http://stackoverflow.com/questions/4244896/dynamic-object-property-name) – Felix Kling Oct 23 '11 at 12:52

1 Answers1

6

Should work fine using such syntax instead:

eval("jsonObj['" + key + "'] = 11");

Actually, eval is not even required:

jsonObj[key] = 11;
Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208
  • Not only that, but using eval is bad. It opens you up to all kinds of security issues (what happens if key contains a quote character, for a start?). – gsnedders Oct 23 '11 at 12:56