Explain Codes LogoExplain Codes Logo

Loading local JSON file

javascript
async-await
fetch-api
json-parsing
Alex KataevbyAlex Kataev·Feb 28, 2025
TLDR

Here's a quick way to load a local JSON file using the Fetch API:

fetch('local.json') .then(res => res.json()) //Gotta get that sweet JSON .then(data => console.log(data)) //Let's make sure we're getting the right stuff .catch(err => console.error('Error:', err)); // Uh-oh :(

Make sure the file path is correct and local file access is enabled to circumvent CORS restrictions.

Deeper Dive: Modern Techniques for Loading Local JSON

Embrace Async: Loading JSON with Fetch and Async/Await

Let's unlock the power of asyhronous JavaScript by using async/await with fetch.

async function loadJSON(path) { try { const response = await fetch(path); // Let's fetch that JSON! if (!response.ok) throw new Error('Network response was not ok'); // Better safe than sorry return await response.json(); // Await for the sweetness } catch (error) { console.error('Fetch error:', error); // Roll out error handling. Who let the dogs out? Woof, woof! } } loadJSON('local.json').then(data => console.log(data)); //Fetch it, boy!

Override Security Protections: Fetch & Local Files

Fetch works great with local files in modern browsers but might run into security constraints. You may need to run your application on a local server to sidestep these. Check your path and ensure local file access is enabled.

Alternative Approaches & Considerations

Handling User Files: FileReader API

Want to let users load their own JSON files without uploading? Try FileReader API. It's older than Fetch, but hey, seasoned things are often tastier!

function handleFileSelect(evt) { const file = evt.target.files[0]; // FileList object const reader = new FileReader(); reader.onload = e => { const data = JSON.parse(e.target.result); // Incoming treasures console.log(data); }; reader.onerror = (e) => { console.error('FileReader error:', e); // Public service announcement, err handled! }; reader.readAsText(file); // Open sesame! } document.getElementById('file-input').addEventListener('change', handleFileSelect, false);

Attach this script to an html input element of type file and you're good to go!

Key Details: JSON Structure

The JSON format is quite strict. Keys must be surrounded by double quotes and no trailing commas are allowed. Else, we risk a parsing error.

Import Assertions (ES2022)

import data from './local.json' assert { type: 'json' }; // Straight to business, no messing around console.log(data); // Here's your data, sir

Security Pitfall: Avoid eval()

Never use eval() for parsing JSON. It's a gateway for code injection vulnerability.

Performance Considerations: JSON in <script> Tags

Enbedding JSON into a <script> tag could affect heap size and cause your app to slow or crash. Keep performance in mind!