Search code examples
javascriptjqueryjsonrestflickr

Use JSON output from Flickr to display images from search


I need to display the images on my site from a JSON request.

I have the JSON:

https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=6a970fbb976a06193676f88ef2722cc8&text=sampletext&sort=relevance&privacy_filter=1&safe_search=1&per_page=5&page=1&format=json&nojsoncallback=1

And I have the format I need to put the photo URL in: https://www.flickr.com/services/api/misc.urls.html

But I don't know how I would loop through that, I found some examples similar, but I am still having trouble seeing what I need.

I am using JavaScript/jQuery to pull the info.

I figure I would have this in a loop.

CurrentPhotoUrl = 'https://farm'+CurrentPhotoFarm+'.staticflickr.com/'+CurrentPhotoServer+'/'+CurrentPhotoId+'_'+CurrentPhotoSecret+'_n.jpg'

But each of those variables would need to be populated with an value from the element. I would need to loop through all 5 elements that are in the JSON.

Any help on how to create this loop would be greatly appreciated.


Solution

  • Try this code

    var n = JSON.parse(x)  //x is the json returned from the url.
    var _s = n.photos.photo;
    for(var z = 0 ; z < n.photos.photo.length ; z++)
    {
       var CurrentPhotoUrl = 'https://farm'+_s[z]['farm']+'.staticflickr.com/'+_s[z]['server']+'/'+_s[z]['id']+'_'+_s[z]['secret']+'_n.jpg'
       console.log(CurrentPhotoUrl);  
    } 
    

    Edit ( With actual JQUERY AJAX call )

        var n ='';
     $.ajax({url: "https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=6a970fbb976a06193676f88ef2722cc8&text=sampletext&sort=relevance&privacy_filter=1&safe_search=1&per_page=5&page=1&format=json&nojsoncallback=1", success: function(result){
    
            console.log(result);
            n = result;
            var _s = n.photos.photo;
            for(var z = 0 ; z < n.photos.photo.length ; z++)
            {
               var CurrentPhotoUrl = 'https://farm'+_s[z]['farm']+'.staticflickr.com/'+_s[z]['server']+'/'+_s[z]['id']+'_'+_s[z]['secret']+'_n.jpg'
               console.log(CurrentPhotoUrl);  
            }  
    
    
        }});
    

    Output:

    https://farm8.staticflickr.com/7198/6847644027_ed69abc879_n.jpg https://farm3.staticflickr.com/2517/3905485164_84cb437a29_n.jpg https://farm1.staticflickr.com/292/32625991395_58d1f16cea_n.jpg https://farm9.staticflickr.com/8181/7909857670_a64e1dd2b2_n.jpg https://farm9.staticflickr.com/8143/7682898986_ec78701508_n.jpg