Skip to main content
edited for readability
Source Link
the Tin Man
  • 160.9k
  • 44
  • 222
  • 308

This seems to be the issue:

An input that is received, via ajaxAjax websocket etc, and it is always gonnawill be in String format - but, but you need to know if it is JSON.parsableJSON.parsable. ToubleThe touble is, that if you always run it through a JSON.parseJSON.parse, the program MAY continue 'successfully'"successfully" but you'll still see an error thrown in the console with the dreaded "Error: unexpected token 'x'""Error: unexpected token 'x'".

var data; try { data = JSON.parse(jqxhr.responseText); } catch (_error) {} data || (data = { message: 'Server error, please retry' }); 

This seems to be the issue:

An input is received, via ajax websocket etc, and it is always gonna be in String format - but you need to know if it is JSON.parsable. Touble is, that if you always run it through a JSON.parse, the program MAY continue 'successfully' but you'll still see an error thrown in the console with the dreaded "Error: unexpected token 'x'".

var data; try { data = JSON.parse(jqxhr.responseText); } catch (_error) {} data || (data = { message: 'Server error, please retry' }); 

This seems to be the issue:

An input that is received via Ajax websocket etc, and it will be in String format, but you need to know if it is JSON.parsable. The touble is, if you always run it through JSON.parse, the program MAY continue "successfully" but you'll still see an error thrown in the console with the dreaded "Error: unexpected token 'x'".

var data; try { data = JSON.parse(jqxhr.responseText); } catch (_error) {} data || (data = { message: 'Server error, please retry' }); 
simple short answer
Source Link
Dorian
  • 24.2k
  • 9
  • 130
  • 116

Here's what I tend to do (but its very kludgy):

var data = (data[0] === '{' || data[0] === '[') ? JSON.parse(data) : data; 

Any insight on a sure catch-all way without errors?

ps. this is kludgy, don't up-vote.

EDIT:

After months of dealing with this issue here and there, it seems the best approach is to use try/catch() and use your own error handling (even if initially its just a console log et cetera):

  try { data = JSON.parse("a"jqxhr.responseText); // Produces a SyntaxError } catch (error) { // Handle the error  console.log(error.message_error); } 

Unfortunately, there's not really elegant degradation for this that I'm aware of.

EDIT

Elegant Degradation ... That I'm Aware Of

The best approach would come from our friends Gang of Four: "Encapsulate what varies" -- and use our parsify function:

var good = JSON.stringify({ value: 'Is an Object' }); var well = JSON.stringify([ 'Is', 'an', 'Object' ]); var bad1 = undefined; var bad2 = 'cannnot parse'; var data = good; function|| parsify(value) { var re = /\{.*\}|\[.*\]/g; var harness = { data: value } , json = JSON.stringify(harness) , parsed = JSON.parse(json) , parsified = parsed.data; var isJSON = !!(parsified && re.test(parsified));  if (!isJSON) parsified = JSON.stringify({ NaO: true }) return parsified; }  var parsified = parsify(data); var response = parsified; var parsed = JSON.parse(response); var value = parsed.value; var NaO = parsed.NaO; if (NaO) console.log('#bunk', 'Not an Object'); else console.log('#parsified',message: 'parsified','Server responseerror, parsed,please value);retry' 

Throw that into your browser, you'll see that you can change data to any value and safely parse out an object. This way, you'll always get back the same type that you're expecting -- along with a NaO property which you can check if necessary. There's a lot of convenience to this function, but you could strip it down to its bare essentials if you prefer.


Also, if I need a quick hack that isn't quite as ugly, feel free to try

if ({ '{': true, '[': true }[ data[0] ]) JSON.parse(data); 

Here's what I tend to do (but its very kludgy):

var data = (data[0] === '{' || data[0] === '[') ? JSON.parse(data) : data; 

Any insight on a sure catch-all way without errors?

ps. this is kludgy, don't up-vote.

EDIT:

After months of dealing with this issue here and there, it seems the best approach is to use try/catch() and use your own error handling (even if initially its just a console log et cetera):

try { JSON.parse("a"); // Produces a SyntaxError } catch (error) { // Handle the error  console.log(error.message); } 

Unfortunately, there's not really elegant degradation for this that I'm aware of.

EDIT

Elegant Degradation ... That I'm Aware Of

The best approach would come from our friends Gang of Four: "Encapsulate what varies" -- and use our parsify function:

var good = JSON.stringify({ value: 'Is an Object' }); var well = JSON.stringify([ 'Is', 'an', 'Object' ]); var bad1 = undefined; var bad2 = 'cannnot parse'; var data = good; function parsify(value) { var re = /\{.*\}|\[.*\]/g; var harness = { data: value } , json = JSON.stringify(harness) , parsed = JSON.parse(json) , parsified = parsed.data; var isJSON = !!(parsified && re.test(parsified));  if (!isJSON) parsified = JSON.stringify({ NaO: true }) return parsified; }  var parsified = parsify(data); var response = parsified; var parsed = JSON.parse(response); var value = parsed.value; var NaO = parsed.NaO; if (NaO) console.log('#bunk', 'Not an Object'); else console.log('#parsified', 'parsified', response, parsed, value); 

Throw that into your browser, you'll see that you can change data to any value and safely parse out an object. This way, you'll always get back the same type that you're expecting -- along with a NaO property which you can check if necessary. There's a lot of convenience to this function, but you could strip it down to its bare essentials if you prefer.


Also, if I need a quick hack that isn't quite as ugly, feel free to try

if ({ '{': true, '[': true }[ data[0] ]) JSON.parse(data); 
var data;   try { data = JSON.parse(jqxhr.responseText); } catch (_error) {} data || (data = { message: 'Server error, please retry' }); 
Cleaner version
Source Link
Cody
  • 10.1k
  • 4
  • 65
  • 48

Also, if I need a quick hack that isn't quite as ugly, feel free to try

if ({ '{': true, '[': true }[ data[0] ]) JSON.parse(data); 

Also, if I need a quick hack that isn't quite as ugly, feel free to try

if ({ '{': true, '[': true }[ data[0] ]) JSON.parse(data); 
more elegant solution
Source Link
Cody
  • 10.1k
  • 4
  • 65
  • 48
Loading
added try catch
Source Link
Cody
  • 10.1k
  • 4
  • 65
  • 48
Loading
missplaced ']' in code
Source Link
oHo
  • 55.1k
  • 30
  • 175
  • 209
Loading
Source Link
Cody
  • 10.1k
  • 4
  • 65
  • 48
Loading