0

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

3 Answers 3

1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

i tried this but i have an error saying 'require is not defined'
Are you using it on the client side or server side?
0

Try

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

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

1 Comment

i tried this but i have an error saying 'require is not defined'
0

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);

11 Comments

It still doesn't work, i don't know why but I still have this message "script.js:5 Uncaught ReferenceError: require is not defined", i'm sad
and i still have this message "Uncaught SyntaxError: Unexpected token ':'" for my json file
@RégisLeRégisseur are you using it in the client side or server side? can you show a code snippet
@RégisLeRégisseur have a look at this thread stackoverflow.com/questions/19059580/…
i use it in the client side
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.