Home / Blog / Web Data / How to Read a JSON File in JavaScript
Detailed guide on reading and handling JSON files, common pitfalls to avoid, and best practices to follow.
JSON (JavaScript Object Notation) is the universal format for data communication between servers and web applications. This article provides a detailed guide on reading and handling JSON files, common pitfalls to avoid, and best practices to follow.
JSON is a text-based, lightweight data communication format that is easy for humans to read and write and for machines to parse and generate. It is built on two simple data structures:
A collection of key/value pairs (which is commonly represented as an object, dictionary, hash table, or associative array in various programming languages).An ordered list of values (which is commonly represented as an array, list, or sequence).Here are some of the common examples of JSON objects.
{ "id": 1, "title": "Introduction to JSON" }
[ { "id": 1, "title": "Introduction to JSON" }, { "id": 2, "title": "Advanced JSON Techniques" } ]
{ "user": { "id": 1, "name": "Jane Doe", "roles": ["admin", "editor"] } }
JSON’s simple syntax makes it ideal for data exchange between servers and web applications. Here are some key advantages you can get from using JSON:
While JSON data are often transferred over a network or directly embedded into JavaScript source code, there can be situations in which you need to read JSON data from a local file. For example, external JSON files can be used as configuration files, user preferences for personalized settings, localization data for translations, sample data for testing, and data seeding for initializing databases.
In this example, I will be using JavaScript FileReader API to read JSON files.
First, you must create an input element of the file type in an HTML file. This will help you in browsing the JSON file for reading.
<input type="file" id="fileInput" accept=".json"> <p id="jsonOutput"></p>
Next, you need to add an event listener to the file input element to capture the file selection event.
const fileInput = document.getElementById('fileInput'); fileInput.addEventListener('change', () => { const file = fileInput.files[0]; readJSONFile(file); });
This function will handle the actual reading and parsing of the JSON file using the FileReader API.
function readJSONFile(file) { const fileReader = new FileReader(); fileReader.onload = () => { try { const jsonData = JSON.parse(fileReader.result); document.getElementById('jsonOutput').textContent = JSON.stringify(jsonData, null, 2); } catch (error) { console.error('Error parsing JSON file:', error); } }; fileReader.onerror = () => { console.error('Error reading JSON file'); }; fileReader.readAsText(file); }
Here’s what’s happening in the readJSONFile function:
onload
JSON.parse
fileReader.result
onerror
readAsText
Once you’ve read and parsed your JSON file, the JSON data becomes accessible and can be manipulated just like any JavaScript object. Here are a few common tasks you might perform with JSON data:
You can get the properties of a JSON object just like you would a regular JavaScript object using bracket or dot notation.
const person = { "name": "John Doe", "age": 30,"email": "john.doe@example.com" }; console.log(person.name); console.log(person['age']);
If your JSON data contains arrays, you can iterate over them using loops or array methods like forEach, map, filter, etc.
const people = [ { "name": "John Doe", "age": 30 }, { "name": "Jane Smith", "age": 25 }, { "name": "Bob Johnson", "age": 40 } ]; people.forEach(person => { console.log(${person.name} is ${person.age} years old.); });
You can modify the properties of a JSON object or elements of a JSON array just like you would with regular JavaScript objects and arrays.
const person = {"name": "John Doe","age": 30,"email": "john.doe@example.com" }; person.age = 31;
You can filter or sort, JSON data using array methods like filter and sort according to certain criteria.
const people = [ { "name": "John Doe", "age": 30 }, { "name": "Jane Smith", "age": 25 }, { "name": "Bob Johnson", "age": 40 } ]; const youngPeople = people.filter(person => person.age < 30); console.log(youngPeople); // Output: [{ name: 'Jane Smith', age: 25 }] const sortedPeople = people.sort((a, b) => a.age - b.age); console.log(sortedPeople); // Output: [{ name 30 }, { name: 'Bob Johnson', age: 40 }]
After successfully reading and parsing JSON data, you must take the necessary steps to avoid common pitfalls and ensure smooth and error-free data handling. Here are a few common mistakes developers often make:
JSON syntax must follow strict rules, such as using double quotes for keys and values and not allowing trailing commas. The data should also be of the expected type.
{ "name": "John" // Missing Comma (X) "age": 30 // Missing Comma (X) "isStudent": "false" // Should be a boolean (X) }
Deeply nested JSON objects can make data access and manipulation more complex and error-prone.
{ "user": { "profile": { "name": "John", "age": 30, "address": { "street": "123 Main St", "city": "Anytown" } } } }
Working with large JSON files can cause performance issues, such as long load times and high memory usage. You can resolve this by paginating the data or using a streaming approach to process the file incrementally.
Despite taking every step to avoid known pitfalls, you can still face unexpected issues when working with JSON files. Therefore, handling errors gracefully is crucial to prevent severe problems like application crashes. Here are some tips and techniques to help you manage errors and debug JSON-related issues:
Ensure that the JSON file is correctly formatted. This can be done using online JSON validators like JSONLint to check for syntax errors before processing the file. Proper JSON format includes enclosing keys in double quotes, using commas to separate key-value pairs, and avoiding trailing commas. Also, wrap the parsing code in a try/catch block when calling JSON.parse.
try { const json = JSON.parse(jsonString); } catch (error) { console.error('Invalid JSON format:', error); }
Before attempting to read and validate a JSON file, confirm that the user has selected a file. You can verify that a file has been chosen by using the property “file” of the input element type: file, and you can ensure it’s also a JSON by checking its extension and mime type.
It’s important to inform users if there is an error when loading or parsing the JSON file. This can be done through alerts and notifications.
try { const json = JSON.parse(e.target.result); console.log('JSON data:', json); } catch (error) { alert('Error parsing JSON: ' + error.message); }
Use developer tools (eg: Chrome Developer Tools) to log and inspect JSON data. For example, you can use console.log() to output the JSON object and inspect its structure and contents.
console.log('Parsed JSON:', json);
Convert JSON objects to a string using JSON.stringify() to make them easier to read and inspect.
console.log('Stringified JSON:', JSON.stringify(json, null, 2));
Break down complex JSON structures into smaller parts to debug issues.
console.log('User Info:', json.user); console.log('User Roles:', json.user.roles);
Code maintainability, performance, and security are important when working with JSON data. Here are some of the best practices you need to keep in mind.
While constructing JSON data structures, use property names that properly show the meaning of the saved data. This will make your code more readable and easier for other programmers to understand.
Bad Example
{ "n": "George" "a": 25 "s" : false }
Good Example
{ "name": "George" "age": 25 "isStudent" : false }
If your application allows sending or receiving JSON data from external sources such as user input or third-party APIs, you must validate it before processing it. This helps prevent certain security vulnerabilities like code injection attacks and supports handling unexpected, malformed inputs.
function validateJsonInput(jsonString) { try { const data = JSON.parse(jsonString); if (data && typeof data === "object") { // Perform additional validation if necessary return data; } } catch (error) { console.error('Invalid JSON:', error); } return null; } const userInput = '{"name": "John Doe", "age": 30}'; const validData = validateJsonInput(userInput); if (validData) { console.log('Valid JSON data:', validData); } else { console.log('Invalid JSON data'); }
Optimize the size of transferred JSON data during network transfer to enhance performance. To achieve this consider minimizing JSON, removing unused spaces and comments and compressing it before sending.
Before
{ "userId": 1, "firstName": "John", "lastName": "Doe", "email": "john.doe@example.com", "address": { "street": "123 Main St", "city": "Anytown", "postalCode": "12345" }, "isActive": true, "roles": [ "admin", "user" ] }
After
{"userId":1,"firstName":"John","lastName":"Doe","email":"john.doe@example.com","address":{"street":"123 Main St","city":"Anytown","postalCode":"12345"},"isActive":true,"roles":["admin","user"]}
Document your JSON data structures, functions, and any assumptions or conventions you follow to ensure that other developers can easily understand and maintain your code.
This article discussed how to read a JSON file using the FileReader API, common pitfalls to avoid, and best practices for working with JSON data. However, regardless of the best practices and precautions we take when reading JSON files, the outcome will always depend on the quality of the JSON file. Collecting and preparing a large data set from scratch can be challenging and time-consuming.
7 min read
Jonathan Schmidt
9 min read
Ben Keane