Reputation: 3
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>
Upvotes: 0
Views: 1422
Reputation: 6873
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 :(');
}
}
Upvotes: 1
Reputation: 536369
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.
Upvotes: 2
Reputation: 17553
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.
Upvotes: 0