简体   繁体   English

在JSON名称和JSON.parse中使用冒号时出现“意外令牌”

[英]'Unexpected token' when using colon in json name and JSON.parse

I am trying to run the below code but continue to get Uncaught SyntaxError: Unexpected token : error in the console. 我正在尝试运行以下代码,但继续在控制台中出现Uncaught SyntaxError: Unexpected token :错误。 I can not seem to escape the colon in the json name. 我似乎无法在json名称中转义冒号。

<p id="demo"></p>

<script>
var text = '{"employees":[' +
'{"first:Name":"John","lastName":"Doe" },' +
'{"first:Name":"Anna","lastName":"Smith" },' +
'{"first:Name":"Peter","lastName":"Jones" }]}';

obj = JSON.parse(text);
document.getElementById("demo").innerHTML =
text.employees[1].first:Name ;

</script>

Any help to resolve this would be great. 解决该问题的任何帮助都将非常有用。 Ultimately the JSON will be coming from a web response so can not change the text. 最终,JSON将来自网络响应,因此无法更改文本。

document.getElementById("demo").innerHTML = text.employees[1].first:Name;
                                                                   ^__error here

Use string representation of object property 使用对象属性的字符串表示形式

document.getElementById("demo").innerHTML = text.employees[1]['first:Name']

or remove : from you object 或删除:从你的对象

{"first:Name":"John","lastName":"Doe" }
       ^___ is this intentional?

text.employees[1].first:Name ; is no valid JavaScript, you'll need to access the key like this: 不是有效的JavaScript,您需要按以下方式访问密钥:

text.employees[1]['first:Name'];

You get Unexpected token : because JS was expected a dot notation when instead found a : . 你得到Unexpected token :因为JS是预期点符号代替时发现:

You can solve this issue by using bracket notation in order to access the property first:Name for your object. 您可以通过使用方bracket notation来解决此问题,以便首先访问属性first:Name对象的first:Name

More information can be found here: 更多信息可以在这里找到:

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_accessors https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_accessors

You example fixed: 您的示例已修复:

 var text = '{"employees":[' + '{"first:Name":"John","lastName":"Doe" },' + '{"first:Name":"Anna","lastName":"Smith" },' + '{"first:Name":"Peter","lastName":"Jones" }]}'; var obj = JSON.parse(text); document.getElementById("demo").innerHTML = obj.employees[1]['first:Name']; 
 <dv id="demo"></dv> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM