我有一個帶有這個物件的 json 檔案:
{
"fontFamily": "Roboto",
"color": "red",
"backgroundColor": "green",
"textForExample": "Hello world i'm a text that's used to display an exemple for my creator."
}
當我決議它時,我的控制臺中有一個錯誤,上面寫著“infosFile.json:2 Uncaught SyntaxError: Unexpected token ':'” 然后當我嘗試在我的 Javascript 中使用它時,我收到了這條訊息控制臺:“infosFile 未定義”,我不明白問題出在哪里
uj5u.com熱心網友回復:
json 是有效的。您可以通過以下鏈接檢查您的 json 檔案是否有效:https : //jsonformatter.curiousconcept.com/
問題可能是為了使用 JavaScript 從您的計算機讀取 json,您需要安裝 NodeJS。你可以從這里下載 NodeJS:https : //nodejs.org/en/
您可以像這樣使用 NodeJS 讀取 json。
const fs = require('fs');
let rawdata = fs.readFileSync('<path/yourFileName>.json');
let data = JSON.parse(rawdata);
console.log(data);
uj5u.com熱心網友回復:
嘗試
const info = require('infosFile.json');
console.log(JSON.parse(info)) // should output valid data
uj5u.com熱心網友回復:
確保您有正確的路徑來訪問您的 JSON 檔案
使用require("")訪問您的 json 檔案并將您的放在雙引號內
使用JSON.parse()讀取并將其存盤在變數中
const json_file = require("./json/test.json");
const data = JSON.parse(json_file);
您也可以使用
const data_stringified = JSON.stringify(data);
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/385205.html
標籤:javascript json 解析
