简体   繁体   English

未捕获到的SyntaxError:意外令牌'

[英]Uncaught SyntaxError: Unexpected token '

I have a array of object inside double quotes when i tried to parse to array it is getting an error as 当我尝试解析为数组时,我在双引号内有一个对象数组,这是一个错误

Uncaught SyntaxError: Unexpected token ' 未捕获到的SyntaxError:意外令牌'

var test = "[{'key' :'D', 'value': 'Deceased Date'},{'key' :'R', 'value': 'Retired Date'},{'key' :'T', 'value': 'Terminated Date'}]";
JSON.parse(test);

I've tried with this below code too. 我也尝试过下面的代码。

$.parseJSON(test);

No single quotes in JSON for a string. 字符串中JSON中没有单引号。 You should be doing this instead: 您应该这样做:

var test = '[{"key" :"D", "value": "Deceased Date"},{"key" :"R", "value": "Retired Date"},{"key" :"T", "value": "Terminated Date"}]';
JSON.parse(test);

In JSON only double quotes are valid. 在JSON中,仅双引号有效。

You can find the standard on JSON.org 您可以在JSON.org上找到标准

A value can be a string in double quotes , or a number, or true or false or null, or an object or an array. 值可以是带双引号的字符串,也可以是数字,也可以是true或false或null,或者是对象或数组。 These structures can be nested. 这些结构可以嵌套。

In other words, no strings in single quotes. 换句话说,单引号中没有字符串。

Single quote doesn't make a valid json string. 单引号不会产生有效的json字符串。 They should be wrapped within double quotes: 它们应该用双引号引起来:

var test = '[{"key" :"D", "value": "Deceased Date"},{"key" :"R", "value": "Retired Date"},{"key" :"T", "value": "Terminated Date"}]';
JSON.parse(test);

Hey fairly simple fix. 嘿,很简单的解决方法。

No quotations around your array its just var x = [stuff in array] It's already an object you don't need to parse it to json. 数组周围没有引号,只是var x = [数组中的内容]它已经是一个对象,您无需将其解析为json。 To view it simply loop through your array. 要查看它,只需遍历数组即可。

var test = [
        {'key' :'D', 'value': 'Deceased Date'},
        {'key' :'R', 'value': 'Retired Date'},
        {'key' :'T', 'value': 'Terminated Date'}
      ];

 for(var i = 0; i < test.length; i++){
  console.log(test[i])
}

try this (in case you cannot change the test string, if it is coming from external source) 试试看(如果您不能更改测试字符串,如果它来自外部)

var test = "[{'key' :'D', 'value': 'Deceased Date'},{'key' :'R', 'value': 'Retired Date'},{'key' :'T', 'value': 'Terminated Date'}]".split('\'').join('\"');
JSON.parse(test);

just add this at the end of test .split('\\'').join('\\"'); to replace ' with " 只是在测试结束时添加此.split('\\'').join('\\"');更换'"

or to make it more simple 或使其更简单

var test = "[{'key' :'D', 'value': 'Deceased Date'},{'key' :'R', 'value': 'Retired Date'},{'key' :'T', 'value': 'Terminated Date'}]";
test = test..split('\'').join('\"');
    JSON.parse(test);

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

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