Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to convert JSONP format to JSON?

Tags:

android

jsonp

I am trying to parse a response from server and i am new to this topic, Unfortunately it is in JSONP format. I don't know how to parse JSONP format, when i tried with JSON Parser it is returning null value. Can anyone please help me in doing this...

Thanks in Advance.

like image 633
wolverine Avatar asked Apr 23 '12 05:04

wolverine


People also ask

What is difference between JSON and JSONP?

Json is stardard format that is human readable used to transmit information from one server to another server. Jsonp is a json with ability to transmit information to another domain. JSONP is JSON with padding, that is, you put a string at the beginning and a pair of parenthesis around it.

What is JSONP format?

JSONP stands for JSON with Padding. Requesting a file from another domain can cause problems, due to cross-domain policy. Requesting an external script from another domain does not have this problem. JSONP uses this advantage, and request files using the script tag instead of the XMLHttpRequest object.

Can we convert string to JSON?

String data can be easily converted to JSON using the stringify() function, and also it can be done using eval() , which accepts the JavaScript expression that you will learn about in this guide.

Should you use JSONP?

JSONP is still useful for older browser support, but given the security implications, unless you have no choice CORS is the better choice.


1 Answers

JSONP is just JSON wrapped in a JavaScript function call. For instance, something like:

callback({"status":"success", "someVar":1});

So you have a couple of options. If you are using a WebView you can define a function called callback in JavaScript and then just call eval() on the JSONP data. This will invoke the callback function, passing it the parsed JSON object (the eval() does the parsing for you).

Or, if you have the JSONP string in your Java code, the simplest option is probably to extract out the JSON substring, like:

String json = jsonp.substring(jsonp.indexOf("(") + 1, jsonp.lastIndexOf(")"));

That will strip off callback( and );, leaving you with just {"status":"success", "someVar":1}, which should then parse with any standard JSON parser.

like image 157
aroth Avatar answered Sep 21 '22 01:09

aroth