I have a local JSON file with the content:
{"resource":"A","literals":["B","C","D"]}
The file is located at /Users/Documents/workspace/test.json
.
How can I use JavaScript to read the JSON file and print its data to the console? I’m looking for a simple approach to JavaScript read JSON file from a local path and display its contents.
1 Like
I’ve worked a lot with Node.js over the years, and honestly, the easiest way to handle local files is within that environment. When you’re working on backend scripts or CLI tools and you need to do a javascript read json file task, Node.js makes it super straightforward using the built-in fs
module.
const fs = require('fs');
fs.readFile('/Users/Documents/workspace/test.json', 'utf8', (err, data) => {
if (err) {
console.error('Error reading file:', err);
return;
}
const jsonData = JSON.parse(data);
console.log(jsonData);
});
Just make sure your script has access to that file path and you’re good to go.
Great point! But what if you’re working in a browser and want to automate reading the file—without user uploads? I’ve had this come up often when working with mock APIs and dev servers. If you can serve your JSON via HTTP (like from a public
folder or an API endpoint), then the fetch API is super handy for a javascript read json file scenario.
fetch('test.json')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Fetch error:', error));
Just be sure the file is accessible from the same origin—or handle CORS if it’s from another domain. It’s a clean, async way to fetch and use JSON data right inside the browser.
If the JSON file is served via HTTP (like in a dev server)
If you move the JSON file to a public folder and serve it with a local server, you can fetch it like this:
fetch('test.json')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Fetch error:', error));
This assumes test.json is hosted on the same domain or server you’re running the script from.