# Read JSON File in JavaScript: Node and Browser

> Read a JSON file in JavaScript: fs and JSON.parse, import with type json, require, fetch in the browser, plus the real JSON.parse errors and Windows BOM fix.

[Home](https://quanticdata.io/) / [Blog](https://quanticdata.io/blog/) / Read JSON File in JavaScript: Node and Browser

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

Guides · Nov 20, 2026 · 7 min read · By [Aldo Morese](https://quanticdata.io/about/), founder of QuanticData

![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.](https://quanticdata.io/blog/read-json-file-javascript/hero.webp?v=20261120h)

On this page

- [Which method to use](https://quanticdata.io/blog/read-json-file-javascript/#which-method-to-use)
- [Node.js: fs and JSON.parse](https://quanticdata.io/blog/read-json-file-javascript/#node-js-fs-and-json-parse)
- [Node.js: import with { type: 'json' } and require](https://quanticdata.io/blog/read-json-file-javascript/#node-js-import-with-type-json-and-require)
- [In the browser: fetch needs a web server](https://quanticdata.io/blog/read-json-file-javascript/#in-the-browser-fetch-needs-a-web-server)
- [JSON.parse errors and what they mean](https://quanticdata.io/blog/read-json-file-javascript/#json-parse-errors-and-what-they-mean)
- [The reviver argument and large numbers](https://quanticdata.io/blog/read-json-file-javascript/#the-reviver-argument-and-large-numbers)
- [A real use: a JSON file of URLs, fetched through a proxy](https://quanticdata.io/blog/read-json-file-javascript/#a-real-use-a-json-file-of-urls-fetched-through-a-proxy)

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.

**Run it on the free credit.** Every QuanticData account gets $2 of free API usage per month.

[Start free — $2/month included](https://quanticdata.io/signup/?utm_source=blog&utm_medium=website&utm_campaign=blog-lead&utm_content=read-json-file-javascript) · [Explore Web Scraping API](https://quanticdata.io/web-scraping-api/)

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:

```json
{
  "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

```javascript
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

```javascript
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`.

**Try it on your own targets.** Every QuanticData account gets $2 of free API usage per month.

[Start free — $2/month included](https://quanticdata.io/signup/?utm_source=blog&utm_medium=website&utm_campaign=blog-inline&utm_content=read-json-file-javascript) · [Explore Web Scraping API](https://quanticdata.io/web-scraping-api/)

## 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:

```javascript
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:

```javascript
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](https://quanticdata.io/blog/how-to-use-a-proxy-in-nodejs/), [Node fetch with a proxy agent](https://quanticdata.io/blog/node-fetch-proxy-setup/) and [axios with a proxy](https://quanticdata.io/blog/axios-proxy-setup/). Our [residential proxies](https://quanticdata.io/residential-proxies/) come with a [Residential Basic free trial](https://quanticdata.io/residential-proxy-free-trial/), and our [web scraping API](https://quanticdata.io/web-scraping-api/) returns pages as JSON when you would rather not parse HTML at all.

### Sources & further reading

- [MDN: JSON.parse()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse)
- [Node.js docs: fs.readFile](https://nodejs.org/api/fs.html#fspromisesreadfilepath-options)
- [Node.js docs: import attributes and JSON modules](https://nodejs.org/api/esm.html#import-attributes)
- [MDN: Response.json()](https://developer.mozilla.org/en-US/docs/Web/API/Response/json)

## FAQ

Quick answers on read json file javascript.

[Something else? Ask us](mailto:hello@quanticdata.io)

### 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.

[Start free — $2/month included](https://quanticdata.io/signup/?utm_source=blog&utm_medium=website&utm_campaign=blog-end&utm_content=read-json-file-javascript) · [Explore Web Scraping API](https://quanticdata.io/web-scraping-api/)

## Related reading

- [Cheerio Web Scraping in Node.js: 1.x Tutorial](https://quanticdata.io/blog/cheerio-web-scraping/): Guides · Fetch the page with Node's built-in fetch, load it with cheerio.load(), and read it with jQuery-style CSS selectors. Below: a scraper we ran with cheerio 1.2.0 on Node 22 that collected 60 books over 3 pages, the newer $.extract() method, a detail page, CSV output, and requests through residential and mobile proxies.
- [Node Fetch Headers: Set, Read and Defaults](https://quanticdata.io/blog/node-fetch-headers/): Guides · Node's built-in fetch sends six request headers by default, with User-Agent: node. We echoed them on 20 November 2026, directly and through a residential proxy, then set our own, tested every method of the Headers object, and read response headers including several Set-Cookie lines.
- [Supabase Edge Function Web Scraping, Deno, Bun](https://quanticdata.io/blog/supabase-edge-function-web-scraping/): Guides · An Edge Function cannot run a browser, but it can call an API that fetches the page and returns Markdown. Below: a Deno.serve function we ran locally on 20 November 2026, one fetch script that ran unchanged on Deno 2.9.8, Bun 1.4.5 and Node.js 22, where the API key goes, and how to pass a rate limit through to your caller.

---

Source: https://quanticdata.io/blog/read-json-file-javascript/ · Site index for AI: https://quanticdata.io/llms.txt
