How can I use JavaScript to load a JSON file from my desktop? Alternatively, for a more direct approach:

16 Replies, 851 Views

Hey! Yeah, fetch() won't work directly for local files due to browser security restrictions.

If you're just testing, try running a local server like `live-server` (install via npm) or use Python's `python -m http.server`.

Otherwise, you can use the File API to let users manually select the JSON file from their desktop:

```js
const input = document.createElement('input');
input.type = 'file';
input.accept = '.json';
input.onchange = e => {
const file = e.target.files[0];
const reader = new FileReader();
reader.onload = event => console.log(JSON.parse(event.target.result));
reader.readAsText(file);
};
input.click();
```

Hope that helps!

Messages In This Thread



Users browsing this thread: 1 Guest(s)