简体   繁体   English

如何从 javascript 中的 json 文件中读取数据

[英]how to read data from a json file in javascript

I have a json file with this object:我有一个 json 文件和这个 object:

{
    "fontFamily": "Roboto",
    "color": "red",
    "backgroundColor": "green",
    "textForExample": "Hello world i'm a text that's used to display an exemple for my creator."
}

and when i'm parsing it I have an error in my console that says "infosFile.json:2 Uncaught SyntaxError: Unexpected token ':'" and then when I'm trying to use it in my Javascript, I got this message in console: "infosFile is not defined", I don't understand where is the problem当我解析它时,我的控制台中有一个错误,上面写着“infosFile.json:2 Uncaught SyntaxError: Unexpected token ':'”然后当我试图在我的 Javascript 中使用它时,我收到了这条消息控制台:“infosFile is not defined”,我不明白问题出在哪里

The json is valid. json 有效。 You can check if you json file is valid at the following link: https://jsonformatter.curiousconcept.com/您可以在以下链接检查您的 json 文件是否有效: https://jsonformatter.curiousconcept.com/

The problem could be that in order to read json from your computer with JavaScript you need NodeJS installed.问题可能是为了从您的计算机中读取 json JavaScript,您需要安装 NodeJS。 You can download NodeJS from here: https://nodejs.org/en/您可以从这里下载NodeJS:https://nodejs.org/en/

You can read json with NodeJS like this.您可以像这样使用 NodeJS 读取 json。

const fs = require('fs');

let rawdata = fs.readFileSync('<path/yourFileName>.json');
let data = JSON.parse(rawdata);
console.log(data);

Try尝试

const info = require('infosFile.json');

console.log(JSON.parse(info)) // should output valid data

Make sure that you have the right path to access your JSON file确保您具有访问 JSON 文件的正确路径

use require("") to access your json file and put your inside the double quotes使用require("")访问您的 json 文件并将您的放在双引号内

use JSON.parse() to read and store it inside a variable使用JSON.parse()读取并将其存储在变量中

const json_file = require("./json/test.json");
const data = JSON.parse(json_file);

You could also stringify it by using您也可以使用

const data_stringified = JSON.stringify(data);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM