Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining the location of a JSON parse error

I am creating a web application that allows a user to load data in JSON format. I am currently using the following function to read JSON files that I have saved on my local disk:

function retrieveJSON(url, callback)
{
  // this is needed because FireFox tries to parse files as XML
  $.ajaxSetup({ mimeType: "text/plain" });

  // send out an AJAX request and return the result
  $.getJSON(url, function(response) {
    console.log("Data acquired successfully");
    callback(response);
  }).error(function(jqXHR, textStatus, errorThrown) {
    console.log("Error...\n" + textStatus + "\n" + errorThrown);
  });
}

This works perfectly for well-formed JSON data. However, for malformed data, the console log displays the following:

Error...
parsererror
SyntaxError: JSON.parse: unexpected character

This is almost entirely unhelpful because it does not tell me what the unexpected character is or what line number it can be found on. I could use a JSON validator to correct the file on my local disk, but this is not an option when the page is loading files from remote URLs on the web.

How can I obtain the location of any error? I would like to obtain the token if possible, but I need to obtain the line number at minimum. There is a project requirement to display an excerpt of the JSON code to the user and highlight the line where any error occurred.

I am currently using jQuery, but jQuery is not a project requirement, so if another API or JSON parser provides this functionality, I could use that instead.

like image 580
Justin Bailey Avatar asked Oct 22 '12 22:10

Justin Bailey


1 Answers

Yeah, life with deadlines is never easy :).

This might help you out, after couple of hours googling around, I've found jsonlint on Git Hub. It looks promising, it includes a shell script that could be used on server side, and there is a browser JavaScript version of it that seems to be exactly what you were looking for.

Hope that this will help You.

like image 196
Dingo Avatar answered Sep 19 '22 17:09

Dingo