Hi Davide,
I understand that you want to structure the data from a table into a ‘. JSON’ file with the provided format. Please refer the following code to achieve the same.
T = readtable('table.xlsx');
T = T(1, :);
% Convert table to structure
table = table2struct(T);
% Get unique hospital IDs from the table
unique_hospital_ids = unique([table.id_ospedale]);
data = struct();
data.practice_data = [];
for i = 1:numel(unique_hospital_ids)
hospital_id = unique_hospital_ids(i);
index = find([table.id_ospedale] == hospital_id);
hospital = struct();
hospital.id_ospedale = num2str(hospital_id);
hospital.dati_pratiche = [];
for j = 1:numel(index)
practice = struct();
practice.codice_nosologico = num2str(table(index(j)).codice_nosologico);
practice.sesso = num2str(table(index(j)).sesso);
practice.eta = num2str(table(index(j)).eta);
practice.diagnosi_principale = num2str(table(index(j)).diagnosi_principale);
% Cell Array
concurrent_diagnoses = {};
diagnosis = struct();
diagnosis.diagnois_concomitante1 = num2str(table(index(j)).diagnois_concomitante1);
concurrent_diagnoses{end+1} = diagnosis;
diagnosis = struct();
diagnosis.diagnois_concomitante2 = num2str(table(index(j)).diagnois_concomitante2);
concurrent_diagnoses{end+1} = diagnosis;
diagnosis = struct();
diagnosis.diagnois_concomitante3 = num2str(table(index(j)).diagnois_concomitante3);
concurrent_diagnoses{end+1} = diagnosis;
practice.diagnosi_concomitanti = concurrent_diagnoses;
practice.DRG_calcolato = num2str(table(index(j)).DRG_calcolato);
hospital.dati_pratiche = [hospital.dati_pratiche, practice];
end
data.practice_data = [data.practice_data, hospital];
end
jsonStr = jsonencode(data);
fid = fopen('output.json', 'w');
if fid == -1
error('Cannot create JSON file');
end
fwrite(fid, jsonStr, 'char');
fclose(fid);
The code above reads dummy data from the attached “.xlsx” sheet. The imported table is converted into a structure and is then organized in the provided format using structs and cell arrays in MATLAB. The data is finally written onto a “.JSON” file.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1469491/image.png)
You can refer to the following documentations for more information on the functions used in the code:
- struct - https://www.mathworks.com/help/matlab/ref/struct.html
- numel - https://www.mathworks.com/help/matlab/ref/double.numel.html
- cell arrays - https://www.mathworks.com/help/matlab/cell-arrays.html
- jsonencode - https://www.mathworks.com/help/matlab/ref/jsonencode.html
Hope this helps.