In Node.js, read the file and parse it: JSON.parse(fs.readFileSync('data.json', 'utf8')), or in an ES module import data from './data.json' with { type: 'json' }. In the browser, serve the file from a web server and use fetch('data.json').then(r => r.json()). JSON.parse turns the JSON text into a JavaScript object.
We ran every snippet below on 20 November 2026 on Windows 11 with Node.js v22.23.2, and the browser part in Chromium 149 driven by Playwright. The output is copied from those runs. The example file is a small scraper config:
{
"country": "us",
"urls": [
"https://ipinfo.io/json",
"https://httpbin.org/json",
"https://quotes.toscrape.com/api/quotes?page=1"
]
}
Which method to use
| Where the code runs | Method | Notes from our run |
|---|---|---|
| Node.js, any module type | JSON.parse(readFileSync(path, 'utf8')) | Simplest; blocks while it reads |
| Node.js, async code | JSON.parse(await readFile(path, 'utf8')) from node:fs/promises | Does not block; same result |
| Node.js, ES module, file known in advance | import data from './data.json' with { type: 'json' } | Worked on Node 22 with no warning |
| Node.js, CommonJS | require('./data.json') | Cached: a second require returns the same object |
| Browser | fetch('data.json') then response.json() | Only over http(s), not from a file:// page |
Node.js: fs and JSON.parse
import { readFileSync } from 'node:fs';
import { readFile } from 'node:fs/promises';
const a = JSON.parse(readFileSync('./config.json', 'utf8'));
console.log(typeof a, Object.keys(a));
// object [ 'country', 'urls' ]
const b = JSON.parse(await readFile(new URL('./config.json', import.meta.url), 'utf8'));
console.log(b.urls[0]);
// https://ipinfo.io/json
- Pass
'utf8', so you get a string. Without it you get a Buffer. - A relative path is relative to the folder you run
nodefrom, not to the script.new URL('./config.json', import.meta.url)resolves it next to the script instead. - Top-level
awaitworks in an ES module (an.mjsfile, or"type": "module"in package.json).
Node.js: import with { type: 'json' } and require
import config from './config.json' with { type: 'json' };
console.log(config.urls.length, 'urls, country', config.country);
// 3 urls, country us
Import attributes (with { type: 'json' }) are the current syntax; older articles show assert { type: 'json' }, the earlier form. Use import when the file is part of your code and known at start-up; use readFile when the path comes at run time or the file changes while the program runs.
In CommonJS, or through createRequire, require('./config.json') parses the file once and caches it. We changed a field on the first result, required the file again, and the second result showed the change: second require sees changed. To re-read a file that changes, use readFile.
In the browser: fetch needs a web server
A page cannot read files from the disk by itself. It asks the server for the JSON file:
fetch('data.json')
.then((r) => { if (!r.ok) throw new Error('HTTP ' + r.status); return r.json(); })
.then((d) => { document.getElementById('out').textContent = 'ok: ' + d.items.length + ' items'; })
.catch((e) => { document.getElementById('out').textContent = 'error: ' + e.name + ': ' + e.message; });
| How the page was opened | Result in Chromium 149 |
|---|---|
Double-clicked, file:///.../index.html | error: TypeError: Failed to fetch; the console said: Fetch API cannot load file:///.../data.json. URL scheme "file" is not supported. |
Served by a local server, http://localhost:8765/ | ok: 3 items |
Any local web server fixes it; ours was a few lines of Node's http module. response.ok matters: fetch does not throw on a 404, so without the check you would try to parse an error page.
JSON.parse errors and what they mean
When the text is not valid JSON, JSON.parse throws a SyntaxError. These are the messages Node 22 gave us:
| Input | Message | Cause |
|---|---|---|
{"a":1,} | Expected double-quoted property name in JSON at position 7 (line 1 column 8) | Trailing comma |
{'a':1} | Expected property name or '}' in JSON at position 1 (line 1 column 2) | Single quotes |
{a:1} | Expected property name or '}' in JSON at position 1 (line 1 column 2) | Unquoted key |
| empty string | Unexpected end of JSON input | Empty file or empty response |
undefined | "undefined" is not valid JSON | A variable that was never set |
{"a":1} then // note | Unexpected non-whitespace character after JSON at position 8 (line 2 column 1) | Comments are not JSON |
| an HTML page | Unexpected token '<', "<!DOCTYPE "... is not valid JSON | The server sent HTML, often an error or block page |
Wrap the parse in try { ... } catch (e) { ... } wherever the text comes from outside your program, and log the first characters of the text: they usually show the cause at once.
The Windows BOM
Windows PowerShell 5.1 writes UTF-8 files with a byte order mark when you use Out-File -Encoding utf8. Node keeps it in the string, and JSON.parse fails on the first character:
const raw = readFileSync('./bom.json', 'utf8');
console.log('first char code', raw.charCodeAt(0)); // first char code 65279
JSON.parse(raw); // SyntaxError: Unexpected token '?', "?{"ok": true}..." is not valid JSON
// (? stands for the invisible BOM character in the message)
JSON.parse(raw.replace(/^\uFEFF/, '')).ok; // true
The character is invisible in the message, which is why this error confuses people. Strip \uFEFF at the start before parsing any file a Windows tool may have written.
The reviver argument and large numbers
- Dates come back as strings. The second argument of
JSON.parsecan convert them: with(k, v) => (k === 'checkedAt' ? new Date(v) : v),checkedAtcame back as a Date (instanceof Datetrue, year 2026). - Numbers above 253 lose precision.
JSON.parse('{"id": 12345678901234567890}').idprinted12345678901234567000. Keep large IDs as strings in the JSON.
A real use: a JSON file of URLs, fetched through a proxy
Scrapers often keep their targets in a JSON file and save results as JSON. This reads config.json, fetches each URL through a QuanticData Residential Basic proxy with undici's ProxyAgent, parses each answer with response.json() and writes the results:
import { readFile, writeFile } from 'node:fs/promises';
import { ProxyAgent } from 'undici';
const config = JSON.parse(await readFile('./config.json', 'utf8'));
const agent = new ProxyAgent({
uri: 'http://residentialboson.quanticdata.io:10000',
token: 'Basic ' + Buffer.from('USER-type-residential-country-us-session-js01-lifetime-30:PASS').toString('base64'),
});
const results = [];
for (const url of config.urls) {
const res = await fetch(url, { dispatcher: agent });
const data = await res.json();
results.push({ url, status: res.status, contentType: res.headers.get('content-type'), keys: Object.keys(data).slice(0, 4) });
}
await writeFile('./results.json', JSON.stringify(results, null, 2));
[
{ url: 'https://ipinfo.io/json', status: 200, contentType: 'application/json', keys: [ 'ip', 'hostname', 'city', 'region' ] },
{ url: 'https://httpbin.org/json', status: 200, contentType: 'application/json', keys: [ 'slideshow' ] },
{ url: 'https://quotes.toscrape.com/api/quotes?page=1', status: 200, contentType: 'application/json', keys: [ 'has_next', 'page', 'quotes', 'tag' ] }
]
written bytes 536
All three answered 200 through the proxy. JSON.stringify(results, null, 2) writes indented JSON; for one record per line (JSON Lines), write JSON.stringify(row) per line and read it back with split('\n').map(JSON.parse), which gave us the same 3 rows. When response.json() meets HTML instead, it throws the same Unexpected token '<' error as JSON.parse: check content-type first.
More on proxies in Node: a proxy in Node.js, Node fetch with a proxy agent and axios with a proxy. Our residential proxies come with a Residential Basic free trial, and our web scraping API returns pages as JSON when you would rather not parse HTML at all.


