1

I am trying to make url shortener that uses goo.gl API. But i stucked when I have to get short URL from JSON response!

After entering this code in Chrome Console:

var longURL = "http://stackoverflow.com/questions/ask"
$.ajax({
                url: 'https://www.googleapis.com/urlshortener/v1/url?shortUrl=http://goo.gl/fbsS&key=AIzaSyANFw1rVq_vnIzT4vVOwIw3fF1qHXV7Mjw',
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                data: '{ longUrl: "' + longURL +'"}',
                dataType: 'json',
                success: function(response) {
                    var result = JSON.parse(response); 
                }
            });

I get following ouptut: enter image description here

I see that my short URL is in resoinseText.id. How to extract it from there?

Vlad Holubiev
  • 4,876
  • 7
  • 44
  • 59

1 Answers1

2

You don't need to call JSON.parse(), because jQuery does that automatically when you specify dataType: 'json'. The value you want will then be in the id property of response.

var longURL = "http://stackoverflow.com/questions/ask"
$.ajax({
    url: 'https://www.googleapis.com/urlshortener/v1/url?shortUrl=http://goo.gl/fbsS&key=AIzaSyANFw1rVq_vnIzT4vVOwIw3fF1qHXV7Mjw',
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    data: '{ longUrl: "' + longURL +'"}',
    dataType: 'json',
    success: function(response) {
        console.log(response.id);
    }
});
Barmar
  • 741,623
  • 53
  • 500
  • 612