Documentation Python quickstart Blog Free tools Enterprise solutions hello@quanticdata.ioLog in

How to read a JSON file in JavaScript, in Node.js and in the browser

Reading a JSON file in JavaScript by environment: in Node.js use fs.readFileSync or fs/promises with JSON.parse, or import with type json; in the browser fetch the file from a web server and call response.json(); the card notes that fetch from a file:// page failed with TypeError: Failed to fetch, and that a UTF-8 BOM breaks JSON.parse.
Reading a JSON file in JavaScript by environment: in Node.js use fs.readFileSync or fs/promises with JSON.parse, or import with type json; in the browser fetch the file from a web server and call response.json(); the card notes that fetch from a file:// page failed with TypeError: Failed to fetch, and that a UTF-8 BOM breaks JSON.parse.

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 runsMethodNotes from our run
Node.js, any module typeJSON.parse(readFileSync(path, 'utf8'))Simplest; blocks while it reads
Node.js, async codeJSON.parse(await readFile(path, 'utf8')) from node:fs/promisesDoes not block; same result
Node.js, ES module, file known in advanceimport data from './data.json' with { type: 'json' }Worked on Node 22 with no warning
Node.js, CommonJSrequire('./data.json')Cached: a second require returns the same object
Browserfetch('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 node from, not to the script. new URL('./config.json', import.meta.url) resolves it next to the script instead.
  • Top-level await works in an ES module (an .mjs file, 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 openedResult in Chromium 149
Double-clicked, file:///.../index.htmlerror: 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:

InputMessageCause
{"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 stringUnexpected end of JSON inputEmpty file or empty response
undefined"undefined" is not valid JSONA variable that was never set
{"a":1} then // noteUnexpected non-whitespace character after JSON at position 8 (line 2 column 1)Comments are not JSON
an HTML pageUnexpected token '<', "<!DOCTYPE "... is not valid JSONThe 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.parse can convert them: with (k, v) => (k === 'checkedAt' ? new Date(v) : v), checkedAt came back as a Date (instanceof Date true, year 2026).
  • Numbers above 253 lose precision. JSON.parse('{"id": 12345678901234567890}').id printed 12345678901234567000. 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.

Sources & further reading

FAQ

Quick answers on read json file javascript.

Something else? Ask us

How do I read a JSON file in JavaScript?

In Node.js: JSON.parse(fs.readFileSync('data.json', 'utf8')), or import data from './data.json' with { type: 'json' } in an ES module. In the browser: fetch('data.json').then(r => r.json()), with the page served over http, not opened as a file.

What does JSON.parse do in JavaScript?

It turns a JSON string into a JavaScript value: an object, an array, a string, a number, true, false or null. It throws a SyntaxError when the text is not valid JSON, and its optional second argument (the reviver) can convert values as they are parsed, such as date strings into Date objects.

Why does fetch fail on a local JSON file?

A page opened from disk (file://) cannot fetch other files: Chromium answered "TypeError: Failed to fetch" and "URL scheme \"file\" is not supported". Serve the folder with any local web server and open the page over http://localhost.

How do I handle JSON.parse errors?

Wrap it in try { JSON.parse(text) } catch (e) { ... } and log the start of the text. The usual causes are a trailing comma, single quotes, comments, an empty response, an HTML page instead of JSON, or a byte order mark at the start of a file written on Windows.

Should I use require or import for a JSON file in Node.js?

In an ES module use import ... with { type: 'json' }; in CommonJS use require. require caches the file: in our test a second call returned the same, already changed object. For a file that changes while the program runs, read it with fs.readFile and JSON.parse each time.

How do I write a JSON file in Node.js?

await writeFile('out.json', JSON.stringify(data, null, 2)) from node:fs/promises. The 2 indents the output; leave it out for compact JSON.

JSON files and JSON APIs, from the country you choose

Residential proxies for fetch and undici, with country targeting and sticky sessions, or pages back as JSON from one API call.

Related reading