how to add string with special character as json key?

我是研究僧i 提交于 2019-12-24 19:08:28

问题


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


回答1:


Should work fine using such syntax instead:

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

Actually, eval is not even required:

jsonObj[key] = 11;


来源:https://stackoverflow.com/questions/7866063/how-to-add-string-with-special-character-as-json-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!