File API - Blob to JSON File API - Blob to JSON json json

File API - Blob to JSON


You should have tried readAsText() instead of readAsArrayBuffer() (JSON is text in the end).

You've also missed to stringify the object (convert to JSON text)

var b = new Blob([JSON.stringify({"test": "toast"})], {type : "application/json"}),    fr = new FileReader();fr.onload = function() {    console.log(JSON.parse(this.result))};fr.readAsText(b);


What you're doing is conceptually wrong. JSON is a string representation of an object, not an object itself. So, when you send a binary representation of JSON over the wire, you're sending a binary representation of the string. There's no way to get around parsing JSON on the client side to convert a JSON string to a JavaScript Object.

You absolutely should always send JSON as text to the client, and you should always call JSON.parse. Nothing else is going to be easy for you.


To convert Blob/File that contains JSON data to a JavaScript object use it:

JSON.parse(await blob.text());

The example:

Select a JSON file, then you can use it in the browser's console (json object).

const input = document.createElement("input");input.type = "file";input.accept = "application/json";document.body.append(input);input.addEventListener("change", async event => {    const json = JSON.parse(await input.files[0].text());    console.log("json", json);    globalThis.json = json;});