admin管理员组文章数量:1389768
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
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
Share Improve this question asked Oct 23, 2011 at 12:13 Ashish AgarwalAshish Agarwal 6,28313 gold badges61 silver badges92 bronze badges 2Uncaught ReferenceError: Invalid left-hand side in assignment
- 1 you don't need to use eval to do this, see wizard's answer below – wong2 Commented Oct 23, 2011 at 12:20
- 1 (a) You are not working with JSON here, only with JavaScript objects. (b) possible duplicate of Dynamic object property name – Felix Kling Commented Oct 23, 2011 at 12:52
1 Answer
Reset to default 6Should work fine using such syntax instead:
eval("jsonObj['" + key + "'] = 11");
Actually, eval
is not even required:
jsonObj[key] = 11;
本文标签: javascripthow to add string with special character as json keyStack Overflow
版权声明:本文标题:javascript - how to add string with special character as json key? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744741497a2622634.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论