While working on pulling data from my server, manipulating it, and attempting to load the string into an object using JSON.parse()
, I encountered an issue with an 'Unexpected Token' error. It was strange because usually Chrome would specify the unexpected token (typically 'o' or similar), but this time it was just a space. This led me to suspect some sort of ASCII encoding problem. Interestingly, if I printed the JSON string to the console using console.log()
and directly pasted it into the code, it parsed without any issues.
var testString = '[ { "pk": 1663, "state": "IO", "group": "ALO", "species": "", "application_link": "" } ]';
var testObject = JSON.parse(testString);
alert(testObject);
The above snippet works as expected, while the following does not:
function hex2ascii(hexx) {
var hex = hexx.toString();
var str = '';
for (var i = 0; i < hex.length; i += 2)
str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
return str;
}
function decodeData(encoded){
var original_string = '';
for (var i = 0; i < encoded.length; i+=2) {
var index = i/2;
var hex_value = encoded[i]+encoded[i+1];
var ochar = hex2ascii(hex_value);
original_string += ochar;
}
return original_string;
}
$.get(url, function(data) {
var testString = decodeData(data);
var testObject = JSON.parse(testString);
alert(testObject);
});
I'm looking for suggestions on how best to troubleshoot this situation.
Edit: Upon further inspection, I noticed several null characters in my string. When converting the JSON string back to hex, I received:
hex_string = ''
for(var i = 0; i < decoded_data.length; i++){
if (i < 10){
alert(decoded_data[i]);
}
hex_string += ascii2hex(decoded_data[i])+' ';
}
console.log(hex_string);
>>>0 0 5b 0 0 7b 0 0 22 0 0 70 0 0 6b 0 0 22 0 0 3a 0 0 20 0 0 31 0 0 36 0 0 36 0 0
Edit again:
After some investigation, I found that the issue stemmed from the concatenation method within the decodeData function. When concatenating using
original_string += ochar;
It was adding numerous null characters. Is there an alternative way to concatenate the string?
Edit answer:
Following further exploration, I discovered that the problem originated from the hex2ascii function, which introduced unnecessary null characters. Since I had borrowed the code from Stack Overflow, it wasn't functioning as expected. By making modifications, I managed to resolve the issue:
function hex2ascii(hexx) {
var hex = hexx.toString();
return String.fromCharCode(parseInt(hex, 16));
}