[英]Read a JSON file and get JSON object back
我正在嘗試將 json 文件讀入我的 Javascript 程序。
配置.json
{
"ProxyURLS": ["xxxx","xxxx"],
"DatabaseURLS": ["xxxx"]
}
JSON文件和index.html在同一個目錄
索引 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 ...
我想獲取 JSON object 並將其傳遞給 getProxyURL function。
當我不包含導入語句時出現此錯誤
(index):13 Uncaught (in promise) ReferenceError: readFile is not defined
at readJsonFile ((index):13:16)
at (index):17:1
當我包含導入語句時出現此錯誤
Uncaught SyntaxError: Cannot use import statement outside a module (at (index):8:1)
看來我需要定義一個“模塊”,但我不確定如何在單個 .html 文件中進行定義。
任何幫助表示贊賞。
我遵循了這個問題的建議: Dynamic import with json file doesn't work typescript
編輯
實施建議的解決方案后:
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();
我收到此錯誤:
Failed to load resource: the server responded with a status of 404 (Not Found)
模塊fs/promises
僅在 node.js 中可用,在瀏覽器中不可用。 您應該使用所有瀏覽器都支持的fetch()
api(除了非常老的瀏覽器,如 Inte.net Explorer)。 您可以在MDN上找到文檔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.