Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a JSON call to an URL?

I'm looking at the following API:

http://wiki.github.com/soundcloud/api/oembed-api

The example they give is

Call:

http://soundcloud.com/oembed?url=http%3A//soundcloud.com/forss/flickermood&format=json 

Response:

{ "html":"<object height=\"81\" ... ", "user":"Forss", "permalink":"http:\/\/soundcloud.com\/forss\/flickermood", "title":"Flickermood", "type":"rich", "provider_url":"http:\/\/soundcloud.com", "description":"From the Soulhack album...", "version":1.0, "user_permalink_url":"http:\/\/soundcloud.com\/forss", "height":81, "provider_name":"Soundcloud", "width":0 } 

What do I have to do to get this JSON object from just an URL?

like image 707
Haroldo Avatar asked Mar 23 '10 11:03

Haroldo


People also ask

Can you put JSON in URL?

JSON→URL text is limited to a subset of the characters allowed in a URL query string. All other characers must be percent encoded. The [ , ] , { , and } characters are not allowed in a URL query string so objects and arrays both begin with ( and end with ) .


2 Answers

A standard http GET request should do it. Then you can use JSON.parse() to make it into a json object.

function Get(yourUrl){     var Httpreq = new XMLHttpRequest(); // a new request     Httpreq.open("GET",yourUrl,false);     Httpreq.send(null);     return Httpreq.responseText;           } 

then

var json_obj = JSON.parse(Get(yourUrl)); console.log("this is the author name: "+json_obj.author_name); 

that's basically it

like image 55
DickFeynman Avatar answered Sep 22 '22 23:09

DickFeynman


It seems they offer a js option for the format parameter, which will return JSONP. You can retrieve JSONP like so:

function getJSONP(url, success) {      var ud = '_' + +new Date,         script = document.createElement('script'),         head = document.getElementsByTagName('head')[0]                 || document.documentElement;      window[ud] = function(data) {         head.removeChild(script);         success && success(data);     };      script.src = url.replace('callback=?', 'callback=' + ud);     head.appendChild(script);  }  getJSONP('http://soundcloud.com/oembed?url=http%3A//soundcloud.com/forss/flickermood&format=js&callback=?', function(data){     console.log(data); });   
like image 42
James Avatar answered Sep 26 '22 23:09

James