Explain Codes LogoExplain Codes Logo

How to read an external local JSON file in JavaScript?

javascript
prompt-engineering
interview-preparation
functions
Anton ShumikhinbyAnton Shumikhin·Oct 24, 2024
TLDR

In JavaScript, you can use the fetch API to load a local JSON file:

fetch('local-file.json') .then(res => res.json()) .then(jsonData => console.log(jsonData));

Switch 'local-file.json' with your specific JSON file path. jsonData is the JavaScript object holding the parsed JSON data.

Reading a local JSON file in JavaScript requires understanding of the environment you're working in. Depending on if your project is server-side with Node.js or a client-side application, different methods would come into action.

Node.js and JSON files

In Node.js environment, the require() function provides an easy way to load and parse JSON files. Here is how to do it:

const jsonData = require('./local-file.json'); console.log(jsonData);

Now, jsonData is a JavaScript object holding the parsed data.

Client-side and its restrictions

In client-side JavaScript, loading files from the local file system might result in a security violation due to cors policy. For this, a web server setup is needed. Also, on every modification, the JSON file requires a server reload due to local caching.

Fetch: the modern standard

Fetch offers an efficient way to handle local JSON files. It is a modern, promise-based mechanism which provides better control and cleaner syntax when dealing with requests/responses.

fetch('path/to/data.json') .then(response => { if (!response.ok) { throw new Error('fetch, more like fetch-error ' + response.statusText); //Only devs understand this pain } return response.json(); }) .then(jsonData => console.log(jsonData)) .catch(error => console.error('Opps, an error slipped through our net: ', error)); // "Try and catch" but we couldn't catch it this time

While small, this piece of code brings in a lot of features and covers many edge cases, giving you a robust and scalable solution.

Delving into other methods

While XMLHttpRequest and fetch are most commonly used, different mechanics exist which cater to various requirements:

"Old school" XMLHttpRequest

XMLHttpRequest has been around before fetch, is also capable of fetching JSON data. However, to parse JSON responses automatically, the responseType must be set to 'json' and the mime type should be overridden to 'application/json'.

let xhr = new XMLHttpRequest(); xhr.overrideMimeType("application/json"); xhr.open('GET', '/path/to/json', true); xhr.responseType = 'json'; xhr.onload = function() { // This is how we handle network error, like a boss! if(xhr.readyState === 4 && xhr.status === 200) console.log(xhr.response); else console.error('ERROR occurs, send a pigeon to report this!'); } xhr.send(null);

When you want more, jQuery has it

For those who are using jQuery, .getJSON() simplifies the process of reading JSON.

$.getJSON('path/to/data.json', function(jsonData) { console.error('Praise the sun, we got the data!', jsonData); // Dark Souls reference right there });

Power of error handling

We all make mistakes, so robust error handling is essential. Do not forget that both JSON.parse() and the xhr requests might throw errors.

Key points to remember

While dealing with JSON, remember these keys points:

  1. Performance: Streaming libraries like Oboe.js could help when dealing with large files.
  2. Security: CORS policy might prevent you from loading a JSON resource.
  3. Flexibility: Besides .json, it's possible to load and parse .txt or .html files if they fit your needs.