web.onassar.com Archive

I can be reached at onassar@gmail.com.

For my open source work, check out github.com/onassar

JSONP vs JSON: amazing for API's.

View more posts

I was doing some search and found http://ajaxian.com/archives/jsonp-json-with-padding as well as http://ajaxpatterns.org/On-Demand_Javascript.

My reason for searching was I was trying to understand why some developers use the term JSONP vs JSON. JSONP standards for JSON with padding. The padding is supposed to give the JSON a little more flexibility. Let me try to convey in my own words the benefit.

JSON is a great storage format for browser community (and even further than that, db storage, but that's for another post). The problem is, with AJAX (terrible name considering XML is hardly ever used; standing for Asynchronous JavaScript and XML), the method for deploying techniques is no longer just the XHR object. It can now be deployed via dynamically written <script /> or <link /> tags. You can write to the browser something like:

<script type="text/javascript">

This is a json object, and while I use the format exclusively for ajax calls, cross domain requests using the <script /> and <link /> tags are becoming more and more common. It's one of the easiest ways to get by the cross domain restrictions set up by browsers (which I think is being alleviated in the next ECMA/JavaScript release, btw), but the issue with just spitting back JSON is it doesn't do anything. Ya, it gets added to the dom (sort of), but it's not even assigned to anyone; my object {'wtf';'yo'} exists, but is basically in limbo. This is JSONP's territory now.

Let's say that JSON string is accessible via olivernassar.com/wtf-yo/

As it stands right now, it'd be spitting out JSON, but if we modified the API to accept a uri such as:


And returned:


That's is JSONP. You can imagine all the possibilities. I've been using it for some time via google/yahoo/facebook API calls, but I never knew the name. I sort of assumed it was a technique that didn't have a name, just a reason. But I suppose client side development needs a name for everything. Too many techniques to keep track of otherwise.

I'm not sure the usefulness of JSONP will be felt by everyone. If you're developing, like most people, internal systems that aren't meant for outside usage (eg. api's) then you can get away with JSON responses via XHR, but the second you cross into the territory of allowing other people access your data via a client side or server side/xml api, JSONP becomes really flexible and powerful, yet easy to implement.