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?
2
Answers
We can create a complex object, with two properties
settings
(which holdsmySettingObject
) andarray
, then we perform the download.On upload we use the
FileReader
,readAsText
to read inUTF-8
format. Finally, we again re-access these properties using the same property names.Full Code:
Stackblitz Demo
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.
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.