Sometimes, we want to convert Blob to JSON with the JavaScript File API.
In this article, we’ll look at how to convert Blob to JSON with the JavaScript File API.
How to convert Blob to JSON with the JavaScript File API?
To convert Blob to JSON with the JavaScript File API, we can use the FileReader
constructor.
For instance, we write:
const b = new Blob([JSON.stringify({
"test": "toast"
})], {
type: "application/json"
})
const fr = new FileReader();
fr.onload = (e) => {
console.log(JSON.parse(e.target.result))
};
fr.readAsText(b);
We create a blob with a JSON string as its content with the Blob
constructor.
We set the type
to 'application/json'
to set the blob type to JSON.
Next, we create a FileReader
instance and set the onload
property to a function that gets the parsed result from e.target.result
.
Then we call JSON.parse
to convert the parsed JSON blob string to an object.
Finally, we call readAsText
with blob b
to read the blob into a string.
Therefore, the console log should log {test: 'toast'}
.
Conclusion
To convert Blob to JSON with the JavaScript File API, we can use the FileReader
constructor.