3

Can someone explain to me how this parse function actually works?

function parseFlickrJson(jsonstring){
    var data=null;

    var jsonFlickrApi=function(d){
        data = d;
    }

    eval(jsonstring);

    return data;
}
0

1 Answer 1

7

JSON is actually valid JavaScript. So all you need to 'decode' it, is to evaluate it as JavaScript (hence the eval). It's also using something known as JSONP http://en.wikipedia.org/wiki/JSONP where more than just JSON is returned.

JSONP is basically JSON wrapped in a function call. The content of a JSONP response might be:

parseResponse({"Name": "Cheeso", Id : 1823, "Rank": 7})

What this means is that when you evaluate JSONP, it will attempt to call a function (in this example parseResponse and in your case jsonFlickrApi). This is why the jsonFlickrApi function must be defined before the eval(jsonstring) occurs.

Sign up to request clarification or add additional context in comments.

2 Comments

so var jsonFlickrApI is not just a custom variable but an actual existing 'thing'? (sorry that must sound a little ignorant...i'm mainly used to Java)
the var jsonFlickrApi = function(d) ... is actually creating an anonymous function and storing a reference to it in jsonFlickrApi (so I suppose it's not really anonymous). eval evaluates a string as if it was source code. Since the response from the Flickr API includes a call to jsonFlickrApi, it's important that that function actually exists, or you'll get an exception.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.