File API - Blob to JSON

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.prepend(input);
input.addEventListener("change", async event => {
    const json = JSON.parse(await input.files[0].text());

    console.log("json", json);
    globalThis.json = 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.


let reader = new FileReader()
      reader.onload = e => {
        if (e.target.readyState === 2) {
          let res = {}
          if (window.TextDecoder) {
            const enc = new TextDecoder('utf-8')
            res = JSON.parse(enc.decode(new Uint8Array(e.target.result))) //转化成json对象
          } else {
            res = JSON.parse(String.fromCharCode.apply(null, new Uint8Array(e.target.result)))
          }

          console.info('import-back:: ', res)


        }
      }

      reader.readAsArrayBuffer(response)