I have a json file with this 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
CodePudding user response:
The json is valid. You can check if you json file is valid at the following link: https://jsonformatter.curiousconcept.com/
The problem could be that in order to read json from your computer with JavaScript you need NodeJS installed. You can download NodeJS from here: https://nodejs.org/en/
You can read json with NodeJS like this.
const fs = require('fs');
let rawdata = fs.readFileSync('<path/yourFileName>.json');
let data = JSON.parse(rawdata);
console.log(data);
CodePudding user response:
Try
const info = require('infosFile.json');
console.log(JSON.parse(info)) // should output valid data
CodePudding user response:
Make sure that you have the right path to access your JSON file
use require("") to access your json file and put your inside the double quotes
use JSON.parse() to read and store it inside a variable
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);