0

I'm requesting JSON file which has an invalid structure:

{}&&{
    "result": {
        "data": "01",
        "id": "02"
    }
}

I can't change JSON. It's on external server. Firebug returns syntax error pointing to the && characters.

What should I do to get this invalid JSON?

My script:

<script src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {      
$.ajax({
url:"http://different-domain.com",
dataType: 'JSONP',
success: parseJSON
function parseJSON(data){
// do stuff with json
}
});
</script> 
Marc Climent
  • 9,434
  • 2
  • 50
  • 55
Lukas
  • 3
  • 3
  • 1
    Why are you getting invalid JSON in the first place? Is there nothing you can do to change that? – Pekka Mar 11 '12 at 12:24
  • If you cannot help returning valid `json`, why try to enforce the `jsonp` data type? Simply don't mention any data type in the ajax request. That would fetch the data but of course, you would not be able to consume it as a `json` object. – Niks Mar 11 '12 at 12:26
  • @NikhilPatil -- JSONP is required in order to issue a cross-domain request. – maxedison Mar 11 '12 at 12:27
  • @ I can't change JSON. It is on external server – Lukas Mar 11 '12 at 14:52
  • @maxedison - Ahh..I missed to read the URL! – Niks Mar 12 '12 at 04:40

3 Answers3

2

The {}&& prefix is chaff designed precisely to stop anyone outside different-domain.com from accessing the data. See this question for the background.

If you want a external interface so you can interact from outside the Same Origin Policy, you will have to get different-domain.com to change their script so that it supports the JSONP callback interface.

Community
  • 1
  • 1
bobince
  • 528,062
  • 107
  • 651
  • 834
1

You can use complete not a success. Than you could get RAW response before error comes. Then you can substr invalid chars while not to got parsed JSON:

$.ajax({
url:"http://different-domain.com",
dataType: 'JSONP',
complete: function(xhr){

    var raw= xhr.responseText
      , json
      , err
      ;

    while(raw.length && err)
    {
      // rewind state
      err= false;
      try {
        //parse JSON
        json= parseJSON(raw);
      }
      catch (e)
      {
        // Mark loop as invalid
        err= true;
      }

      // Get out if json is valid and parsed
      if (!err) break;

      // If loop is not broken try another one time: cut one char from invalid json and go on.
      raw= raw.substr(1);
    }

    if (!err)
    {
      console.log('YAPPPEEEEE :)');
    }
    else
    {
      console.log('NOPE :(');
    }
}
Paul Rumkin
  • 6,737
  • 2
  • 25
  • 35
0

Looks like you want to remove the && and anything that comes before it. Assuming that this is always the case, do the following in the success handler of the $.ajax() method:

succes: function(data){
    var goodJSON = data.slice(4);
    var myObject = $.parseJSON(goodJSON);
}

myObject will now hold the fully parsed JSON.

maxedison
  • 17,243
  • 14
  • 67
  • 114