Home > Software design >  Read a JSON file and get JSON object back
Read a JSON file and get JSON object back

Time:11-27

I am trying to read a json file into my Javascript program.

configuration.json

{
    "ProxyURLS": ["xxxx","xxxx"],
    "DatabaseURLS": ["xxxx"]
}

The JSON file is in the same directory as the index.html

Index html

<!DOCTYPE html>
<html>
<head>
<title>QUBGrader</title>

<script type="text/javascript">

import { readFile } from "fs/promises";
//Define path for configuration readFile

path = "./configuration"
//read file get json
async function readJsonFile(path) {
  const file = await readFile(path, "utf8");
  return JSON.parse(file);
}

readJsonFile("./package.json").then((data) => {
  console.log(data);
  getProxyURL(data);
});



function getProxyURL(data)
{
  console.log("here")
  console.log(data)
}

... file continues ...

I want to obtain the JSON object and pass it to the getProxyURL function.

I get this error when I do not include the import statement

(index):13 Uncaught (in promise) ReferenceError: readFile is not defined
    at readJsonFile ((index):13:16)
    at (index):17:1

I get this error when I do include the import statement

Uncaught SyntaxError: Cannot use import statement outside a module (at (index):8:1)

From googling the error (https://bobbyhadz.com/blog/javascript-syntaxerror-cannot-use-import-statement-outside-module#:~:text=The "SyntaxError: Cannot use import,json for Node.)

It seems that I need to define a "module", but I am not sure how to do that within a single .html file.

Any help appreciated.

I followed advice from this question: Dynamic import with json file doesn't work typescript

EDIT

After implementing suggested solution:

function readJson () {
   // http://localhost:8080
   fetch('./configuration')
   .then(response => {
       if (!response.ok) {
           throw new Error("HTTP error "   response.status);
       }
       return response.json();
   })
   .then(json => {
       getProxyURL(json);
       //console.log(this.users);
   })
   .catch(function () {
       this.dataError = true;
   })
};

readJson();

I get this error:

Failed to load resource: the server responded with a status of 404 (Not Found)

CodePudding user response:

The module fs/promises is only avaiable in node.js and not in browsers. You should use the fetch() api which is supported by all browsers (except very old browsers like Internet Explorer). You can find a documentation on MDN.

  • Related