JSON.parse fails even though there is no problem with the format.

Asked 1 years ago, Updated 1 years ago, 413 views

I'm trying to use electron(v22)+Vue(v3) in JSON.

An error occurs when attempting to parse the uploaded file to the JSON text file.
I thought it might be because of a new line code or space, so I made a JSON with a minimum configuration.
However, the error still occurs.

const text=fs.readFileSync(filePath, 'utf-8');
const json=JSON.parse(text);

The text file tested looks similar to the following:There is no new line code

 {"test":"text"}

The errors that occur are as follows:

SyntaxError: Unexpected token', "{"test":"text"}"is not valid JSON

I added toString, but it was the same.

JSON.parse(text.toString())
SyntaxError: Unexpected token', "{"test":"text"}"is not valid JSON

Writing text statements directly is fine

JSON.parse('{"test":"test"}')
>Object {test:"test"}

I don't know why the error occurs.
What do you think is the cause?

Thank you for your cooperation.

[Additional note]
I have tested various things in the debug console.

It looks the same, but it seems to be recognized that the contents are different.
The character code is UTF-8, and since it's only symbols and alphabets, isn't the character code affected?

I tried typeof(text) and got a string back.

Well, what's really the cause?

Enter a description of the image here

javascript json

2022-12-29 17:42

1 Answers

The target file was UTF-8 with BOM.
Therefore, the first character had a U+FEFF, which caused JSON.parse to fail.

By deleting it with the code below, I was able to make it into JSON without any problems.

let text=waitfs.readFileSync(filePath, 'utf8');
if(text.charCodeAt(0)===0xFEFF){
    text=text.substring(1);
}
const json=JSON.parse(text);

(This is what you pointed out in the comment.)Now that it has been resolved, I will post it as an answer.)


2022-12-30 11:34

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.