We can create a complex object, with two properties settings (which holds mySettingObject) and array, then we perform the download.
downloadFile() {
const mySettingObject = {
qwerty: 1,
};
const myArrayObj = {
settings: mySettingObject,
array: [{ test: 1 }, { test: 2 }, { test: 3 }],
};
const myFileName = 'test';
const blob = new Blob([JSON.stringify(myArrayObj)], {
type: 'application/json',
});
this.saveAs(blob, `${myFileName}.json`);
}
saveAs(blob: any, filename: any) {
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.click();
window.URL.revokeObjectURL(url);
}
On upload we use the FileReader, readAsText to read in UTF-8 format. Finally, we again re-access these properties using the same property names.
onSelectFile(event: any) {
this.selectedFile = event.target.files[0];
const fileReader = new FileReader();
fileReader.readAsText(this.selectedFile, 'UTF-8');
fileReader.onload = () => {
const data = JSON.parse(<string>fileReader.result);
console.log('settings', data.settings);
console.log('settings', data.array);
};
fileReader.onerror = (error) => {
console.log(error);
};
}
Full Code:
import { Component } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
@Component({
selector: 'app-root',
standalone: true,
template: `
<button (click)="downloadFile()">download</button>
<hr/>
<input type='file' (change)="onSelectFile($event)">
`,
})
export class App {
name = 'Angular';
selectedFile: any;
downloadFile() {
const mySettingObject = {
qwerty: 1,
};
const myArrayObj = {
settings: mySettingObject,
array: [{ test: 1 }, { test: 2 }, { test: 3 }],
};
const myFileName = 'test';
const blob = new Blob([JSON.stringify(myArrayObj)], {
type: 'application/json',
});
this.saveAs(blob, `${myFileName}.json`);
}
saveAs(blob: any, filename: any) {
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.click();
window.URL.revokeObjectURL(url);
}
onSelectFile(event: any) {
this.selectedFile = event.target.files[0];
const fileReader = new FileReader();
fileReader.readAsText(this.selectedFile, 'UTF-8');
fileReader.onload = () => {
const data = JSON.parse(<string>fileReader.result);
console.log('settings', data.settings);
console.log('settings', data.array);
};
fileReader.onerror = (error) => {
console.log(error);
};
}
}
bootstrapApplication(App);
new Blob([JSON.stringify([mySettingObject, myArrayObj])], { type: 'application/json' });