Reputation: 17784
I am using a web server that returns JSON
but jquery fails to parse that json and shows following error
Uncaught SyntaxError: Unexpected token ' in JSON at position 1
The data returned by api seems to be fine. I copied the response in my js file and tried to parse it with $.parseJSON
but I get the same error. Here is the code snippet containing returned json
and a call to parseJSON
var jso = "['ADCP1_SNR_CH1','ADCP1_SNR_CH2','ADCP1_SNR_CH3','ADCP1_RADVEL_CH0']";
var dt = $.parseJSON(jso);
My question is, what is wrong with the above json
array? why do I bump into this error?
Upvotes: 0
Views: 52
Reputation: 391
The problem is that single quotes are not valid in JSON. Swap the single and double quotes, like so:
var jso = '["ADCP1_SNR_CH1","ADCP1_SNR_CH2","ADCP1_SNR_CH3","ADCP1_RADVEL_CH0"]';
var dt = $.parseJSON(jso);
Alternatively, you can escape the quotes like this:
var jso = "[\"ADCP1_SNR_CH1\",\"ADCP1_SNR_CH2\",\"ADCP1_SNR_CH3\",\"ADCP1_RADVEL_CH0\"]";
var dt = $.parseJSON(jso);
Upvotes: 2
Reputation: 9157
JSON does not support single quotes ('
). It must use double quotes:
var jso = '["ADCP1_SNR_CH1","ADCP1_SNR_CH2","ADCP1_SNR_CH3","ADCP1_RADVEL_CH0"]';
var dt = $.parseJSON(jso);
console.log(dt);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Upvotes: 2