This article will show you how to read a JSON file into JavaScript as a JSON object – both local and remote files.
What is JSON?
JSON (JavaScript Object Notation) is a file format that stores objects, and arrays of objects, as human-readable text. It’s become the most popular method of storing and transmitting structured data on the internet.
Thousands of APIs (used for mapping, communication, authentication, and many other purposes) use it as the format for submitting and receiving data. Desktop applications also use it to store user data, and databases have adopted it for storing structured data.
It’s everywhere, so you’ll be getting pretty familiar with it no matter what you’re working on. Here’s how it looks:
{ "pets": [ { "name": "Frank", "animal": "Dog", "colour": "Blue" }, { "name": "Jim", "animal": "Cat", "colour": "Green" }, { "name": "Pam", "animal": "Cow", "colour": "Red" } ] }
Above, a list of pets is defined in JSON syntax. If you’ve been working with JavaScript objects, you’ll recognize that it is very similar to the syntax used to define objects and arrays in JavaScript. You can find out more about the JSON syntax itself here.
Parsing JSON in JavaScript
JSON is just text – it needs to be interpreted and converted into objects to be useful in JavaScript.
All of the below methods will do this and return usable objects and arrays as JavaScript objects.
Reading a File at URL from the Browser
If you are building a website and wish to read a JSON file using JavaScript being executed in the browser, it must be read from a URL – even if it’s stored on the same disk, in the same folder, as the JavaScript file being executed.
The fetch function in JavaScript will read the contents of a file at a given URL and has built-in functionality for parsing the JSON into usable JavaScript objects.
var url = 'https://example.com/test.json'; fetch(url) .then(response => response.json()) .then(json => { console.log(json); // Do stuff with the contents of the JSON file here });
Above, fetch is used to retrieve the file at the given URL. The first then statement retrieves the JSON parsed version of the response.
The second then statement then contains the parsed JSON file ready for use – in this case, it’s simply logged to the console for inspection.
Reading a Local File from the Browser
The FileReader object, a relatively recent addition to HTML5 and JavaScript, allows you to read files stored locally on your computer directly into JavaScript running in a browser, without the need to first upload it to a server.
Note, the below example relies heavily on JavaScript Promises – so it’s worth getting familiar with them!
<script> // Function to read the JSON from a file - returns a promise containing the parsed JSON async function readJSONFile(file) { // Function will return a new Promise which will resolve or reject based on whether the JSON file is read and parsed successfully return new Promise((resolve, reject) => { // Define a FileReader Object to read the file let fileReader = new FileReader(); // Specify what the FileReader should do on the successful read of a file fileReader.onload = event => { // If successfully read, resolve the Promise with JSON parsed contents of the file resolve(JSON.parse(event.target.result)) }; // If the file is not successfully read, reject with the error fileReader.onerror = error => reject(error); // Read from the file, which will kick-off the onload or onerror events defined above based on the outcome fileReader.readAsText(file); }); } // Function to be triggered when file input changes async function fileChange(file){ // As readJSONFile is a promise, it must resolve before the contents can be read - in this case logged to the console readJSONFile(file).then(json => console.log(json)); } </script> <!-- File input. When changed, file inputs produce a FileList object (this.files) - the first item within being the first selected file. --> <input type="file" onchange="fileChange(this.files[0])" />
Reading a Local File from Node.js
The fs library in Node.js handles all local file read/write operations. Once it’s been used to read a file, the contents can simply be parsed into JSON:
const fs = require('fs'); let fileText = fs.readFileSync('data.json'); let jsonParsed = JSON.parse(fileText); console.log(jsonParsed);
Reading a Remote file from Node.js
The fetch method outlined above is also the best way to accomplish this from a Node.js environment – give it a shot!
You can also read from remote JSON resources from the Linux command line using cURL.