简体   繁体   中英

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 '

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. 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.

You can find the standard on 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. These structures can be nested.

In other words, no strings in single quotes.

Single quote doesn't make a valid json string. 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. 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 "

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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