Read local JSON file using only Javascript

Hello,

I am trying to read the content of a local JSON file using vanilla Javascript. So far I have only found one method to do this, which is creating a GET request for the local file like this:

var request = new XMLHttpRequest();
request.open("GET", "localFolder/example.json", false);
request.send(null);
var data = JSON.parse(request.responseText);

Is there any other way that doesn’t require a GET request to read a local file?

Thank you in advance.

In node:

// fs: manipulate files
const fs = require('fs');
// Or this way, like in jest...
// import fs from 'fs';

// path: manipulate paths
const path = require('path');
// import path from 'path';

const alerts = fs.readFileSync(
  path.resolve(__dirname, './test/data/alerts.json'),
  {'encoding': 'utf-8'}
);

// Of course you still need to parse the JSON, etc.

This is almost verbatim from a a jest test setup of mine. Use require/import as appropriate.

In the browser, use GET and a development web server. Otherwise you have to disable a lot of browser security to make it work.

I was wondering if there is a different way to do it using pure Javascript without extra libraries or frameworks.

Like for example, a simple way to read documents in C# would be using the ReadAllText method. Does Javascript have something similar?

JavaScript doesn’t really have a standard library, so almost everything is a library/package/add-on. fs is the equivalent to that bit of C#, I assume, knowing nothing of C#. You could always look at the source for fs and path to see how they do it.

The closest analogy is that JS is like C; the language will fit on a sheet of paper, but is not nearly as useful without the standard library (in C) or libraries (in JS).

JSON modules: Stage 3

This works in Chrome but not yet in Firefox (with type="module" on the script). Node has experimental support as well (with or without the flag --experimental-json-modules depending on the version I believe).

import json from './jsonData.json' assert { type: 'json' };

But it’s obviously not something you would want to implement at present time.

I’m wondering about the use case. If it’s in the browser, then you won’t be able to read local files anyway (unless you have user interaction/permission). If it’s on the server, then node’s built-in ‘fs’ is the way to go.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.