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?
Reading From JSON Python has a built-in package called json, which can be used to work with JSON data. It's done by using the JSON module, which provides us with a lot of methods which among loads() and load() methods are gonna help us to read the JSON file.
#1) Apple TextEdit Apple TextEdit comes bundled with Mac OS X and is an open-source text editor. It is a simple program that you can use for reading and editing JSON, XML, OpenDocument, text documents, etc. It also reads and writes .
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With