Imagine a scenario where the source providing your JSONP response is trustworthy and consistently delivers accurate JSONP responses.
This essentially means that you will receive a response in the following format:
functionName(jsonString)
Just like in this example:
Temp([{"XXX":"2","YYY":"3","ZZZ":"4"},{"XXX":"5","YYY":"6","ZZZ":"7"},{"XXX":"1","YYY":"2","ZZZ":"3"}])
Extracting JSON - Approach 1
If you only require the object from the response function parameter, you could approach it like this:
var jsonObject = null;
try
{
var response = 'Temp([{"XXX":"2","YYY":"3","ZZZ":"4"},{"XXX":"5","YYY":"6","ZZZ":"7"},{"XXX":"1","YYY":"2","ZZZ":"3"}])';
var temp = response.split('(');
delete temp[0];
temp = temp.join('(').split(')');
delete temp[temp.length-1];
temp = temp.join(')');
temp = temp.substring(1, temp.length-1);
jsonObject = JSON.parse(temp);
}
catch(ex)
{
}
console.log(jsonObject);
Extracting JSON - Approach 2
Using this method actually enables handling multiple JSON objects as function parameters.
Let's assume you are unaware of the method name the JSONP result is intended to call.
Therefore, we can try something like:
var response = 'Temp([{"XXX":"2","YYY":"3","ZZZ":"4"},{"XXX":"5","YYY":"6","ZZZ":"7"},{"XXX":"1","YYY":"2","ZZZ":"3"}])';
try{
var fnName = response.split('(')[0];
var fn = new Function(fnName, response);
var jsonObject = null;
fn(function(json){
jsonObject = json;
});
console.log(jsonObject);
}
catch(ex){
console.log(ex.message);
}