To parse JSON you already have as text, call JSON.parse(text). To load a JSON file in a browser, fetch its URL and await response.json(); in Node.js, read the local file with node:fs/promises and then parse the returned text. Check HTTP status and handle both file-reading and JSON syntax errors.
Choose the method for where the file lives
The main difference is how you get the file contents. A browser normally requests a file exposed at a URL; Node.js can read a file from the local filesystem. Once you have JSON text, JSON.parse() converts it into a JavaScript value. The result might be an object, array, string, number, boolean, or null, depending on the JSON.
- Browser, served file: use
fetch()and usuallyresponse.json(). - Node.js, local file: use
readFile()fromnode:fs/promisesand thenJSON.parse(). - JSON text already in memory: call
JSON.parse()directly.
Parse JSON already stored as text
JSON.parse() accepts a JSON string and constructs the JavaScript value it describes. It throws a SyntaxError if the input is not valid JSON. See MDN’s JSON.parse() reference.
const text = '{"name":"Mina","active":true,"roles":["editor","admin"]}';
const data = JSON.parse(text);
console.log(data.name); // Mina
console.log(data.roles[0]); // editor
JSON syntax is not identical to JavaScript object-literal syntax. JSON property names and strings must use double quotes; comments, trailing commas, and single-quoted strings are not valid JSON.
Quick wins for a faster PC:
Repair Windows errors before they cause bigger problemsFix Now →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Clear out junk files and repair common Windows errorsFree Scan →#1 Best Overall
- Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
- Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
- Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
- Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
- 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
// Valid JSON text:
const valid = '{"count":3}';
// Not valid JSON text:
const invalid = "{'count': 3}";
JSON.parse(invalid); // SyntaxError
Use a reviver only when values need transforming
The optional second argument to JSON.parse() is a reviver function. It runs as parsed properties are visited and can transform or remove values. For ordinary file loading, omit it; transform after parsing unless you specifically need conversion during parsing.
Load a JSON file in a browser
Browser JavaScript generally reads a JSON file that your page can request over HTTP, such as a file deployed at /data/example.json. Fetch is asynchronous. A successful fetch() promise does not necessarily mean the server returned a successful status: for example, a 404 response still fulfills the promise. Check response.ok before reading the body. See MDN’s Fetch API guide.
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 inside an async function, or use top-level await where your script runs as a module and the environment supports it. response.json() reads and parses the response body; it returns a promise for the resulting value.
Rank #2
- 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
- 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
- Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
- 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
- What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
Read text first for clearer diagnostics
If you need to inspect the response body, log it, or apply a reviver, read it as text and then parse it yourself. This makes the read and parse stages explicit:
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 & 11Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minuteasync 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);
}
Use the text-first form when you need to distinguish an HTTP failure from malformed JSON or want to capture the raw response while debugging. Do not call both response.text() and response.json() on the same response body; body-reading methods consume the body.
Check the response when the format is uncertain
A JSON file is commonly served with the application/json MIME type. When an endpoint might return an HTML error page or another format, inspect the status and, if useful, the Content-Type response header before attempting to parse. A header check is a diagnostic aid, not proof that the body is valid JSON; parsing remains the definitive check.
Rank #3
- Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
- Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
- Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
- Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
- What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
Read and parse a local JSON file in Node.js
For asynchronous filesystem access, use readFile from node:fs/promises, request UTF-8 text, and parse that text. Save this example in an ES module and make sure ./data.json is present relative to the process’s working directory.
import { readFile } from 'node:fs/promises';
const text = await readFile('./data.json', 'utf8');
const data = JSON.parse(text);
console.log(data);
There are two separate failure points: the read can reject if the path is wrong or access is denied, and parsing can throw if the file contents are not valid JSON. Node.js documents asynchronous, callback-based, and synchronous filesystem APIs in its file system documentation.
CommonJS version
If your project uses CommonJS, require the promise-based API and handle the returned promise:
Rank #4
- Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
- Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
- Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
- Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
- Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
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);
Use synchronous reads sparingly
readFileSync() is available from node:fs, but it blocks the Node.js event loop until the operation completes. That can be acceptable for a small, one-time startup read in a command-line script; it is usually a poor choice for request handling or other code that needs to remain responsive.
Handle errors without hiding their cause
Catch errors at a boundary where you can report or recover from them. Keep the read/request failure distinct from the parse failure so a useful message identifies what went wrong.
async function loadJsonFromFile(path) {
let text;
try {
text = await readFile(path, 'utf8');
} catch (error) {
throw new Error(`Could not read ${path}: ${error.message}`, { cause: error });
}
try {
return JSON.parse(text);
} catch (error) {
throw new Error(`Invalid JSON in ${path}: ${error.message}`, { cause: error });
}
}
The example uses readFile from node:fs/promises as in the Node.js example above. If your runtime does not support the cause option for Error, omit that second argument and retain the descriptive message.
Free tools Windows power users keep installed
One-click scans. No signup required.
Best Value
- 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
- Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
- Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
- HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
- What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
Typical failure and what to check
- HTTP error: inspect
response.statusand confirm the URL, route, and server response. Fetch does not reject solely because the status is 404 or another HTTP error. - Unexpected response body: inspect the response text and content type. A server may return an HTML error page where JSON was expected.
SyntaxError: locate the reported position in the actual response or file. Check for single quotes, unquoted keys, comments, trailing commas, truncation, or other non-JSON syntax.- Node filesystem error: verify the path, current working directory, permissions, and that the file exists; catch the rejected read promise.
- Wrong encoding or corrupt data: read the intended text encoding and ensure the file was completely written and contains JSON rather than a different format.
Choose between direct parsing, fetch, and text-first parsing
| Situation | Use | Why |
|---|---|---|
| JSON text already available | JSON.parse(text) |
Parses an in-memory string into a JavaScript value. |
| Browser needs a served JSON resource | fetch(url), check response.ok, then response.json() |
Fetch handles the asynchronous request and JSON body parsing. |
| Browser needs raw response text or custom parse handling | fetch(url), check status, response.text(), then JSON.parse(text) |
Keeps response reading separate from syntax parsing for inspection. |
| Node.js needs a local file | readFile(path, 'utf8'), then JSON.parse(text) |
Reads the filesystem asynchronously and then parses the text. |
| One-time small Node.js read where blocking is acceptable | Synchronous node:fs API |
Simpler control flow, but blocks the event loop while reading. |
Large JSON files and performance
The examples above buffer the whole file or response before parsing. For a typical configuration file or modest API response, that is straightforward. For a very large network response, response.text() waits for the complete body, and response.json() likewise returns only after consuming and parsing the response. Fetch exposes response streams that can be processed in chunks when incremental handling is needed; chunk processing requires additional logic and does not make a single all-at-once JSON.parse() operation incremental.
Choose streaming only when the data size and processing needs justify the added complexity. If the application ultimately needs one complete JavaScript object, buffering and parsing may still be the appropriate approach. The Fetch response-body methods and streaming behavior are documented by MDN’s Using Fetch guide.
Or skip the browser setup
If the goal is a clean screenshot of a page that displays JSON or related content, ScreenshotNeo can return an image or PDF from one GET request. It accepts cookie banners like a visitor and removes 60+ known consent platforms, newsletter popups, and chat widgets before capture; those steps can be turned off. Bot checks and CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and the response reports the page verdict and billing status. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf to AI agents.
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 options. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000 screenshots. ScreenshotNeo also supports PNG, JPEG, WebP, and PDF output. Sign up for 1,000 free screenshots a month, with no card required.
Recommended Free Tools
Frequently Asked Questions
Does JSON.parse() read a file from disk by itself?
No. It parses a string; use a filesystem API in Node.js or fetch a served resource in a browser to obtain that string or response.
Can I use comments or single quotes in a JSON file?
No. Standard JSON does not allow comments, and JSON strings and property names require double quotes.
Why does fetch not throw for a 404 response?
Fetch can fulfill with an HTTP error response. Check response.ok and the status before parsing the body.
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.

