How to read a JSON file in JavaScript
Reading JSON files in JavaScript is essential for loading configuration data, localization files, and external data sources in web applications. As the creator of CoreUI with extensive JavaScript experience since 2000, I’ve used JSON file loading for internationalization, configuration management, and data imports in production applications. The most straightforward approach uses the fetch API to retrieve the JSON file and automatically parse it. This method provides clean asynchronous file loading while handling parsing errors gracefully.
Use fetch API with the json() method to read and parse JSON files automatically.
async function readJsonFile(filePath) {
try {
const response = await fetch(filePath)
if (!response.ok) {
throw new Error(`Failed to load file: ${response.status}`)
}
const jsonData = await response.json()
return jsonData
} catch (error) {
console.error('Error reading JSON file:', error)
throw error
}
}
// Usage
readJsonFile('config/settings.json')
.then(data => {
console.log('Configuration loaded:', data)
// Use the JSON data in your application
})
.catch(error => {
console.error('Failed to load configuration:', error)
})
This code uses fetch to retrieve the JSON file from the specified path, then calls the json() method which automatically parses the JSON content. The function includes error handling for both network failures and invalid JSON parsing. The async/await syntax makes the code readable while maintaining proper error propagation.
Best Practice Note:
This is the approach we use in CoreUI applications for loading localization files and configuration data. Always handle network errors and JSON parsing failures separately to provide meaningful error messages to users and developers.



