To parse JSON, pass its text to JSON.parse(). For a JSON file served to a browser, use fetch() and usually await response.json(); for a file on disk in Node.js, read it with node:fs/promises and then call JSON.parse(). The right method depends on where the file lives: browser JavaScript generally fetches a URL, while Node.js can read a local path.
Choose the method for where the file lives
| Situation | Read the file with | Parse the result with |
|---|---|---|
| A JSON resource served by a website to browser JavaScript | fetch(url) |
Usually await response.json(); use response.text() plus JSON.parse() when you need the raw text or custom parsing control |
| A local file read by a Node.js program | readFile(path, 'utf8') from node:fs/promises |
JSON.parse(text) |
| JSON text already held in a JavaScript string | No file read is needed | JSON.parse(text) |
These are two separate jobs: getting the file contents and turning JSON text into a JavaScript value. A file extension such as .json does not itself parse the file. JSON files are normally text and commonly served with the application/json MIME type.
Parse JSON text with JSON.parse()
JSON.parse(text) converts a JSON string into the JavaScript value described by that string. The result may be an object, array, string, number, boolean, or null. If the input is not valid JSON, parsing throws a SyntaxError; it does not quietly repair malformed input.
const text = '{"name":"Ada","active":true,"count":3}';
const data = JSON.parse(text);
console.log(data.name); // Ada
console.log(data.active); // true
JSON syntax is not identical to JavaScript object-literal syntax. Property names and string values must use double quotes. For example, {'name': 'Ada'} is JavaScript-like text, not valid JSON; {"name":"Ada"} is valid JSON text. Do not use eval() as a substitute for parsing JSON.
#1 Best Overall
Use a reviver only when you need to transform parsed values
JSON.parse() accepts an optional reviver function. It lets you inspect or transform values as the JSON structure is parsed. Leave it out for ordinary data loading; add one only when you have a specific conversion rule, because otherwise it makes the parse path harder to understand.
const data = JSON.parse(text, (key, value) => {
if (key === 'enabled' && value === 1) return true;
return value;
});
The example is only appropriate if the input format deliberately represents the enabled field as 1. A reviver does not make invalid JSON valid: malformed syntax still causes parsing to fail.
Load a JSON file in the browser
Browser code normally loads a JSON file over a URL. fetch() is asynchronous and returns a Promise. Its Promise can fulfill even when the server responds with an HTTP error such as 404, so check response.ok before treating the body as the expected JSON resource.
async function loadJson(url) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return response.json();
}
const data = await loadJson('/data/example.json');
console.log(data);
Use this in an async function, or in a module environment that supports top-level await. Replace /data/example.json with the URL at which your server makes the file available. The browser does not use this code to open an arbitrary path from the user’s computer; browser access to local files is not the same as Node.js filesystem access.
PC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchRank #2
When response.json() is the simplest choice
Use await response.json() when you want the response body parsed as JSON and do not need to inspect its original text. The method is asynchronous. If the body is not parseable JSON, it rejects rather than returning a parsed value. Check the HTTP status first so a server-generated error page or error payload is not mistaken for the file you expected.
When to read text and call JSON.parse() explicitly
Use response.text() followed by JSON.parse() if you need to log the raw response, keep a copy of the text, separate response reading from parsing, or pass a reviver.
async function loadJsonWithExplicitParse(url) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const text = await response.text();
return JSON.parse(text);
}
This makes the two stages visible: first the browser reads the response body as text, then JavaScript parses that string. It does not make invalid JSON acceptable; the parse step still throws a SyntaxError.
Read and parse a local JSON file in Node.js
In Node.js, use the asynchronous readFile() function from node:fs/promises. Specify 'utf8' so the result is a JavaScript string rather than a buffer, then parse it.
The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →ES modules
import { readFile } from 'node:fs/promises';
const text = await readFile('./data.json', 'utf8');
const data = JSON.parse(text);
console.log(data);
This example assumes the file is at ./data.json relative to the process’s working directory. If your program is launched from a different directory, a relative path may point somewhere other than the directory containing the source file; use a path appropriate to how you run the program.
CommonJS
const { readFile } = require('node:fs/promises');
async function loadJson(path) {
const text = await readFile(path, 'utf8');
return JSON.parse(text);
}
loadJson('./data.json')
.then(console.log)
.catch(console.error);
The file read and parsing can fail for different reasons. The Promise rejects if the file cannot be read, while JSON.parse() throws if the text is malformed. Catching the Promise rejection handles either failure at the call site, but separating the operations can make diagnosis clearer.
Should you use a synchronous file read?
Node.js also provides synchronous filesystem APIs, including readFileSync. They block the event loop and further JavaScript execution until the read finishes. That can be acceptable for a small, one-time startup read where blocking is intentional. For ordinary application work, the asynchronous Promise API avoids holding up other JavaScript execution while the file operation completes.
Handle errors without hiding their cause
Use error handling that tells you which stage failed. For a browser request, distinguish an HTTP status failure from a body or JSON parsing failure. In Node.js, distinguish a filesystem read failure from malformed JSON. A broad catch that only says “could not load data” makes it harder to decide what to fix.
Rank #4
async function loadJsonWithContext(url) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Could not fetch JSON: HTTP ${response.status}`);
}
const text = await response.text();
try {
return JSON.parse(text);
} catch (error) {
if (error instanceof SyntaxError) {
throw new Error(`Response was not valid JSON: ${error.message}`);
}
throw error;
}
}
For Node.js, keep the read outside the parse try block if you want filesystem failures and syntax failures to remain distinct:
import { readFile } from 'node:fs/promises';
async function loadJson(path) {
const text = await readFile(path, 'utf8');
try {
return JSON.parse(text);
} catch (error) {
if (error instanceof SyntaxError) {
throw new Error(`Invalid JSON in ${path}: ${error.message}`);
}
throw error;
}
}
Troubleshoot common JSON parsing failures
- The browser reports an HTTP error. Inspect
response.statusand confirm that the URL points to the intended resource. Fetch does not automatically reject just because a server returned an HTTP error status; checkresponse.ok. response.json()rejects. The body may not be valid JSON, or the server may have returned a different format. Read it withresponse.text()while diagnosing and inspect the actual payload before parsing it.JSON.parse()throwsSyntaxError. Check the raw text around the reported location. Common causes include single quotes, unquoted property names, trailing commas, or a response that contains an HTML error page instead of JSON. JSON requires double-quoted names and strings.- Node.js cannot find or read the file. Handle the rejected
readFile()Promise and verify the path and the process’s working directory. This is a filesystem failure, not a JSON syntax problem. - The output is not the object you expected. JSON can describe values other than objects, including arrays and
null. Inspect the parsed value and its shape rather than assuming every JSON document has top-level properties.
Memory and large responses
response.text() waits for the complete response body before returning a string, and ordinary response.json() likewise gives you a parsed result rather than an incremental sequence of records. For a very large network response, Fetch exposes response streams that can be processed in chunks. Streaming requires code designed to consume chunks and handle the format incrementally; calling JSON.parse() on each arbitrary chunk is not a valid replacement because a chunk may split a JSON token or structure.
For modest files, buffering the complete text and parsing it is usually the direct approach. For large data, consider whether the server can provide smaller pages or records, or whether your application can process a stream. The appropriate strategy depends on the response format and what your program needs to do with each part.
Or skip the browser setup
If your goal is to capture a page rather than parse a JSON data file, ScreenshotNeo offers a one-request screenshot API. It is not a JSON parser: it returns a screenshot or PDF of a webpage. Cookie banners, popups, and chat widgets are removed before the shot; bot checks, blank pages, and failed loads are never billed. Its MCP server lets AI agents take screenshots, and 1,000 screenshots a month are free with no card; paid plans start at $5 for 3,000.
Free tools Windows power users keep installed
One-click scans. No signup required.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
See the ScreenshotNeo API documentation for request details. Try ScreenshotNeo if page screenshots are the task, and sign up for 1,000 free screenshots a month with no card.
Best Value
Frequently Asked Questions
Does JSON.parse() return a JavaScript object every time?
No. It returns the JavaScript value described by the JSON text, which can be an object, array, string, number, boolean, or null.
Can I parse a JSON file directly from its path in browser JavaScript?
The browser examples here fetch a URL served by a website. Reading a local filesystem path is the Node.js case; browser code does not use Node’s filesystem APIs.
Does response.json() check whether the request returned a successful HTTP status?
No. Check response.ok yourself before parsing, because Fetch can fulfill for HTTP error statuses such as 404.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

