How to Parse a JSON File in JavaScript (Browser & Node.js)
In this article
Parsing a JSON file in JavaScript means converting the file's text content into a usable JavaScript object. In the browser you fetch the file over HTTP, while in Node.js you can read it from the filesystem. Both environments use the built-in JSON.parse() method to do the actual conversion. This guide walks you through both scenarios step by step, including error handling and common pitfalls.
What You'll Need
- A JSON file (e.g.,
data.json) with valid JSON syntax. - For the browser: a local web server (or any HTTP server) to serve the file, because
fetch()does not work withfile://URLs in most browsers. - For Node.js: Node.js installed (version 12 or later recommended for
fs.promises). - A text editor and a way to run JavaScript (browser console or terminal).
Step-by-Step
In the Browser (using fetch)
- Place your JSON file in a web-accessible folder. For example, put
data.jsonin the same directory as your HTML file. - Start a local web server. If you have Python, run
python -m http.serverin that folder. If you have Node.js, you can usenpx serveor write a simple server. This step is required because browsers blockfetch()on local files for security reasons. - Write a fetch call in your JavaScript. In your script (inside
<script>tags or an external JS file), do:fetch('data.json') .then(response => { if (!response.ok) { throw new Error('HTTP error ' + response.status); } return response.json(); }) .then(data => { console.log(data); // Now you have a JavaScript object }) .catch(error => console.error('Error:', error)); - Use the parsed object. The
datavariable is now a plain JavaScript object or array, depending on the JSON content. You can access properties likedata.nameor iterate over arrays.
In Node.js (using fs module)
- Create or obtain your JSON file. For example,
data.jsonin the same directory as your script. - Use
fs.readFileSync(synchronous) orfs.promises.readFile(async). For most cases, async is better to avoid blocking. Here's the async version:const fs = require('fs'); async function readJSON() { try { const fileContent = await fs.promises.readFile('data.json', 'utf8'); const data = JSON.parse(fileContent); console.log(data); } catch (error) { console.error('Error:', error); } } readJSON(); - Alternatively, use
require()for simple cases. If the JSON file is static and you don't need to reload it, you can doconst data = require('./data.json');– Node.js will parse it automatically. However, this caches the file, so it won't reflect changes during runtime. - Handle the parsed object. Just like in the browser,
datais now a JavaScript object you can use.
Common Mistakes
- Forgetting to specify encoding in Node.js. If you omit
'utf8',readFilereturns a Buffer, andJSON.parsewill throw aSyntaxErrorbecause it expects a string. - Using
fetchonfile://URLs. Browsers block this due to CORS. Always use a local server. - Not checking
response.okin fetch. If the file is missing (404),response.json()will still try to parse the error page, leading to a confusing error. - Trailing commas or comments in JSON. JSON does not allow trailing commas or
//comments. Use a JSON validator to check. - Using
require()for dynamic files. It caches the file, so if you modify the JSON file during runtime, you won't see the changes unless you delete the cache.
Tips
- Always wrap
JSON.parse()in a try-catch block to handle malformed JSON gracefully. - Use
JSON.stringify(data, null, 2)to pretty-print an object back to JSON for debugging. - In Node.js, prefer
fs.promisesoverfs.readFileSyncfor non-blocking behavior in server applications. - If you're dealing with very large JSON files, consider streaming parsing (e.g., using
JSONStreamin Node.js) to avoid memory issues. - In the browser, cache the parsed data if you need it multiple times – don't fetch it repeatedly.
Troubleshooting
SyntaxError: Unexpected token – Your JSON file is invalid. Check for missing commas, quotes, or extra characters. Use an online JSON validator or JSON.parse() in the console to locate the error line.
TypeError: Cannot read property 'x' of undefined – The parsed object doesn't have the expected structure. Log the parsed data to the console and inspect its keys.
Fetch fails with CORS error – You're likely opening the HTML file directly from disk. Start a local server (e.g., python -m http.server) and access via http://localhost:8000.
Node.js says 'Cannot find module' – The file path is wrong. Use an absolute path or ensure the relative path is correct from the current working directory.
JSON.parse gives an empty object – The file might be empty or contain only whitespace. Check the file size and content.
Frequently Asked Questions
Can I parse JSON from a URL in Node.js?
Yes, you can use the fetch() API (available in Node.js 18+) or libraries like axios to get JSON from a URL, then parse it with response.json().
What's the difference between JSON.parse() and eval() for JSON?
Never use eval() – it executes arbitrary code. JSON.parse() only reads data and is safe and fast.
How do I handle a JSON file that is an array?
Parsing works the same way. The result will be a JavaScript array. You can then use array.forEach() or other array methods.
Can I parse JSON from a string in the browser without fetch?
Absolutely. If you already have a JSON string (e.g., from a text input), just call JSON.parse(yourString).
Is there a way to parse JSON asynchronously?
The JSON.parse() function is synchronous, but you can wrap it in a Promise or use it inside an async function. The file reading (fetch or fs) is what's asynchronous.
What if my JSON file is very large?
Consider streaming parsing in Node.js (e.g., using JSONStream) or using a web worker in the browser to avoid blocking the UI thread. For most cases, JSON.parse() is fine up to a few megabytes.