LWC: Import JSON from a zip Static Resource
You can use a simple XMLHttpRequest:
import MYJSON from '@salesforce/resourceUrl/myjsonfile';
...
var xhr = new XMLHttpRequest();
xhr.open("GET", MYJSON);
xhr.onload = () => this.data = xhr.responseText;
xhr.send(null);
You can put your JSON file in a Javascript file. An example is shown below. I created a file called test.js and uploaded to static resource with name test
"use strict"
window.myObj = {
"colors": [
{
"color": "black",
"category": "hue",
"type": "primary",
"code": {
"rgba": [255,255,255,1],
"hex": "#000"
}
},
{
"color": "white",
"category": "value",
"code": {
"rgba": [0,0,0,1],
"hex": "#FFF"
}
},
{
"color": "red",
"category": "hue",
"type": "primary",
"code": {
"rgba": [255,0,0,1],
"hex": "#FF0"
}
},
{
"color": "blue",
"category": "hue",
"type": "primary",
"code": {
"rgba": [0,0,255,1],
"hex": "#00F"
}
},
{
"color": "yellow",
"category": "hue",
"type": "primary",
"code": {
"rgba": [255,255,0,1],
"hex": "#FF0"
}
},
{
"color": "green",
"category": "hue",
"type": "secondary",
"code": {
"rgba": [0,255,0,1],
"hex": "#0F0"
}
},
]
};
You can now load this JSON into webcomponent using platformResourceLoader
as below
import { LightningElement } from 'lwc';
import { loadScript } from 'lightning/platformResourceLoader';
import testlib from '@salesforce/resourceUrl/testjs';
export default class Testcmp extends LightningElement {
libInitialized = false;
renderedCallback() {
if (this.libInitialized) {
return;
}
this.d3Initialized = true;
loadScript(this, testlib).then(() => {
console.log(window.myObj);
});
}
}
Note that there is also another way to do this is by using a service component only to hold data export it as Javascript function.