[SalesForce] Accessing Static Resource Contents from Lightning JS Controller

I am attempting to set the value of a lightning component attribute with the type JSON to the contents of a JSON static resource file. I am using the following to set the attribute from the client side controller.

cmp.set('v.attribute', $A.get('$Resource.StaticResourceName'));

This, however, is producing the file path string, not the data itself. I have checked How does one access the file contents themselves to set it to a variable?

Best Answer

You can get the data with a simple HTTP request:

({
    init: function(component, event, helper) {
        var path = $A.get("$Resource.StaticResourceName");
        var req = new XMLHttpRequest();
        req.open("GET", path);
        req.addEventListener("load", $A.getCallback(function() {
            component.set("v.attribute", req.response);
        }));
        req.send(null);
    }
})