jsonangularfileblob

How to write and read different JSON objects as BLOB in file using angular


In my Angular program, have a class called myObj and an array called myArrayObj, that contains many instances of myObj.

I am currently storing it into Blob and write into file, as shown below.

    const blob = new Blob([JSON.stringify([myArrayObj])], { type: 'application/json' });
    saveAs(blob, `${myFileName}.json`);

To retrieve content from file, I have another set of codes.

    const fileReader = new FileReader();
    fileReader.onload = (e) => {
       const content = e.target?.result;
       if (typeof content === 'string') {
          const myArrayObj = JSON.parse(content);
       }

My problem is that I want to save a single setting object (mySettingObject) into the file, before this array. How do I do that? How do I retrieve the setting object and array later?


Solution

  • My problem is that I want to save a single setting object (mySettingObject) into the file, before this array.

    You can't. At least, not directly.

    Normally, JSON parsers only work on one root object. Therefore, you'd have to serialize an entire object that contains your array as well.

    JSON.stringify({
      mySettingsObject,
      myArrayObject
    });
    

    In this case, there's a singular root object that you can reference properties on, which is perfectly fine.

    An alternative... there is a variant of JSON that uses line delimiters called ND-JSON. This allows multiple root objects, but the usual use of it is for multiple objects of the same or similar type. While this isn't a requirement, I'd think your use case is inappropriate.