I am trying to read a first set of element from JSON file during browse event. I am able to read JSON file successfully when it contains data as an array of elements but when my input JSON contains only one element my code is not working.
My ask is to read the first set of element from JSON file.
I am able to read below structure using my code.
[
{
"id": 1,
"disabled": false,
"selected": false
},
{
"id": 2,
"disabled": true,
"selected": false
},
{
"id": 3,
"disabled": false,
"selected": true
}
]
But I am unable to read below if JSON file contains only one element.
{
"id": 1,
"disabled": false,
"selected": false
}
My angular code:
handleFileInput(file: FileList) {
this.isError = "";
let fileType = file.item(0).name.split(".");
if ((fileType[1] == "json") && fileType.length == 2) {
this.fileToUpload = file.item(0);
this.fileName = file.item(0).name;
let filereader = new FileReader();
filereader.readAsText(file.item(0), "UTF-8");
filereader.onload = (e) => {
}
filereader.onerror = (error) => {
console.log(error);
}
}
let tempDataList = await this.readFileData();
let jsonElements = Object.keys(tempDataList[0]);
}
readFileData() {
return new Promise<any>((resolve, reject) => {
let jsonData: any[] = [];
let filereader = new FileReader();
filereader.readAsText(this.fileToUpload, "UTF-8");
filereader.onload = (e) => {
jsonData = JSON.parse(filereader.result.toString());
resolve(jsonData);
}
filereader.onerror = (error) => {
console.log(error);
}
});
}
Below line throws an error:
let jsonElements = Object.keys(tempDataList[0]);
CodePudding user response:
Add a check to see if the data is an array. If not then it's one element.
if (Array.isArray(tempDataList)){
let jsonElements = Object.keys(tempDataList[0]);
} else {
let jsonElements = Object.keys(tempDataList);
}