I am working with lightning web components and I have static json files. I want to work with them in LWC in my javascript file.
its not a zipped file.
I want the files to be in static resource because of the cache advantage.
I saw examples for css and script files, but not for json.
Any help will be appreciated.
Best Answer
This is actually surprisingly easy to achieve using standard JavaScript functionality that is supported by the Salesforce Locker Service; the XMLHttpRequest. You can check what is supported by opening the Locker API Viewer then searching for the feature of interest.
Static resources can be referenced by special imports in LWC using their base name (without their file-type-extension). This import in the LWC component is of the form:
This actually defines a variable (here jsonData) that contains the URL to the specified resource.
It is therefore really easy to then use an XMLHttpRequest to load the content of that file into the component. In your case you want to load the file and parse it as JSON.
Here is an example of this in action. First, the JSON file as a static resource "data.json":
Next the "jsonLoader" LWC JavaScript:
This code illustrates a synchronous loading of the data in the connectedCallback, but you could implement this with asynchronous behaviour instead. The JSON is obtained, parsed and stored in a tracked property to ensure that the LWC's template is re-rendered when the value is set or updated.
The LWC's template here is a trivial example:
The LWC's metadata exposes this component so it is available in the Lightning App Builder, specifically in home and record pages:
If you add this LWC and the static resource to your org you can then drop this (exposed) component into a home page or record page and will see the text, including the JSON data in that page: