José M.
José M.

Reputation: 623

Using FileReader to read a JSON file?

I'm trying to read a JSON file I have, uploaded by the user, and try to copy it to an array. However, with a .readAsText(), the return I get has the formatting of a string (obviously), such as including \" and \n and other string-like properties.

Is there a way I can use FileReader (or any other form of reading files, that don't involve a server) to read the JSON file and have it return just the plain JSON?

For example, having it return

[
  {"hello": "world"}
]

or

[{"hello": "world"}]

and not

"[\n{\"hello\": \"world\"}\n]"

?

Edit: I am now aware of the JSON.parse(text) method, but I'm getting an error when parsing the FileReader object

 let fileUploaded = new FileReader();
 fileUploaded.readAsText(MY_JSON_FILE);
 console.log(JSON.parse(fileUploaded));

it returns the error error TS2345: Argument of type 'FileReader' is not assignable to parameter of type 'string'

Can I get what i read with FileReader to another var that is a string, and then parse that new var?

Upvotes: 18

Views: 33737

Answers (1)

guest271314
guest271314

Reputation: 1

The code at the question uses FileReader incorrectly.

FileReader .readAs<Type> operation is asynchronous. FileReader has load and loadend events where the result property of event.target and FileReader instance is the resulting asynchronously processed data.

Do not parse the FileReader object itself.

.readAs<Type> expects a Blob to be passed as parameter, not a JavaScript plain object.

const MY_JSON_FILE = [{
  "hello": "world"
}];

let json = JSON.stringify(MY_JSON_FILE);

const blob = new Blob([json], {type:"application/json"});

const fr = new FileReader();

fr.addEventListener("load", e => {
  console.log(e.target.result, JSON.parse(fr.result))
});

fr.readAsText(blob);

Upvotes: 22

Related Questions