David
David

Reputation: 953

Clean up bad JSON string

I'm trying to use a web service that returns JSON data that JavaScript cannot parse directly. I use a jQuery AJAX call and get the error message "Uncaught SyntaxError: Unexpected token : " in the Chrome developer console. How can I fix this? Here's a sample of what I get from the service:

{
"DepartureBoard":{
    "noNamespaceSchemaLocation":"http://api.vasttrafik.se/v1/hafasRestDepartureBoard.xsd",
    "error":"No journeys found",
    "errorText":"There was no journey found for the requested board or time.",
    "$":""
}
}

Here is my code. The error function below is executed.

$.ajax({
    crossDomain: true,
    type: 'GET',
    contentType: "application/json; charset=utf-8",
    url: myurl,
    dataType: 'jsonp',
    jsonpCallback: 'onSuccess',
    cache: false,
    success: function (data) {
        this.onSuccess( data );
    },
    error: function (data) {
        // prints debug messages now
    }
});

Update: I'm doing a request to a remote resource. This seems to complicate things.

Update 2: Maybe I've been going at this the wrong way. I thought it would be trivial to parse JSON data, but it's seemingly in the wrong format as some have pointed out.

Update 3: I found a workaround. By creating a minimal PHP file with the function call file_get_contents($url) I can do an AJAX call to my own server. With JSONP and some modifications inspired by the answers below, I got it working. (By accident, wrapping everything in minimal .php files instead of .html actually solved another problem; my JavaScript files were being cached.)

Upvotes: 1

Views: 3089

Answers (3)

Bengt
Bengt

Reputation: 26

I'm acctually using the same service, this is how

            var tripQuestion = "https://api.vasttrafik.se/bin/rest.exe/v1/trip?authKey=" + authKey + "&format=json&jsonpCallback=searchForTripJSON" + "&numTrips=6";
            if (time && date) tripQuestion = tripQuestion + "&date=" + date + "&time=" + time;
            if (departure.id) tripQuestion = tripQuestion + "&originId=" + departure.id
            if (destination.id) tripQuestion = tripQuestion + "&destId=" + destination.id
            else tripQuestion = tripQuestion + "&destCoordLat=" + destination.lat+ "&destCoordLong=" + destination.lon+ "&destCoordName=" + destination.name
            $.ajax({
                crossDomain: true,
                type: 'GET',
                async: true,
                contentType: "application/json; charset=utf-8",
                url: tripQuestion,
                dataType: 'jsonp',
                jsonpCallback: 'searchForTripJSON',
                jsonp: false,
                cache: false,
                success: function (data) {
                    //put success code here
                },
                error: function (data) {
                    //put error code here
                },
                complete: function (data) {
                    //put complete code here
                }

hope this helps

Upvotes: 1

Alex Shilman
Alex Shilman

Reputation: 1547

You shouldn't need to parse it. It's already an object. How are you outputting json on server side? Try this client side:

$(document).ready(function() {
    $.getJSON(myurl + '?callback=?', 'param=value',  function(result) {
        console.log(result.DepartureBoard.errorText);
    });
  });

should console out: "There was no journey found for the requested board or time." P.S. if it's PHP on the backend then you should:

$error = array(
"DepartureBoard" => array(
       "noNamespaceSchemaLocation" => "http://yoururl.xsd",
   "error" => "No journeys found",
   "errorText" => "There was no journey found...",
   "$" => ""
     )
);
header('Content-Type: text/javascript; charset=utf8');
echo $_GET['callback'] . '(' . json_encode($error) . ')';

Upvotes: 0

gen_Eric
gen_Eric

Reputation: 227310

You are requesting JSONP, but that's not what is being returned. JSONP is not JSON. JSONP is actually just a JavaScript file. You want the response to be:

onSuccess({
    "DepartureBoard":{
        "noNamespaceSchemaLocation":"http://api.vasttrafik.se/v1/hafasRestDepartureBoard.xsd",
        "error":"No journeys found",
        "errorText":"There was no journey found for the requested board or time.",
        "$":""
    }
});

Note how the object is wrapped in a function call.

Also, some of the parameters in your $.ajax call are incorrect.

The contentType sets the Content-type header of the request, it's the content type of the request body. It has nothing to do with the response. Get rid of it.

The jsonpCallback is only needed if the server doesn't accept a callback parameter as a GET parameter. It's only for if the server uses a hard-coded string as the callback name.

Without it, jQuery will append callback=someFunctionName to your URL and expects that the JSONP response will use that as the callback name.

For example, the JSONP response should be (using PHP as an example here):

echo $_GET['callback'].'('.json_encode($data).');';

Finally, this.onSuccess( data ); inside your success probably doesn't do what you think it does. I suggest removing that line. Inside your success function data will be the object returned from the call.

Upvotes: 2

Related Questions