Create excel file from json variable value
显示 更早的评论
I think there is an easy solution to this but I keep running into the same issue.
I want to create an excel file from a json value. The json file is stored in subject-specific folders (all with the same general path).
All json variables appear at the same line in the json file

My current code:
clear
subjs = {'SUB2114'
'SUB2116'
'SUB2118'};
subjs=subjs.';
for i=1:length(subjs)
%cd to folder with json files
cd (['/Volumes/myDirectory/' subjs{i} '/folder/']);
%read AP json file
jsonText = fileread('Fieldmapap.json');
jsonData = jsondecode(jsonText);
ap = jsonData.PhaseEncodingDirection;
ap=ap.';
% write json (not needed?)
encodedJSON = jsonencode(ap);
jsonText2 = jsonencode(jsonData);
fid = fopen('J_script_test.json', 'w');
fprintf(fid, encodedJSON);
fclose(fid);
end %subject loop
%write table with subjects in first column and encodedJSON value in second column
T=cell2table([subjs encodedJSON]);
writetable(T,'Tester.csv');
I have also tried the mytable function (below) with no positive results.
mytable=table('Size',[3 2],'VariableTypes',{'cellstr';'cellstr'},'VariableNames',{'subjects';'direction'});
mytable{i,'subjects'} = {subjs};
mytable{i,'direction'} = {ap};
I keep getting an output that lists subjects horizontally with the last subjects direction value.

I think I am missing something simple (like, i+1 function), but do not know!
Any help would be appreciated!
2 个评论
Rik
2024-6-6
Your loop is overwriting the results, and it would seem that your alternative would also be placed inside the loop, causing the variable to be recreated every iteration.
What is it exactly you want to achieve? Do you want a cell array with the subject ID in one column and the phase encoding in the second column?
Nikki
2024-6-6
采纳的回答
更多回答(2 个)
Eric Sofen
2024-6-6
I'm roughing this a bit since I don't have your JSON data files, but the below approach puts your file names in a table, then uses rowfun to iterate over the table, reading the corresponding JSON file and returning the corresponding phase encoding.
subjs = {'SUB2114'
'SUB2116'
'SUB2118'};
t = table(subjs);
ph = rowfun(@getPhaseEncodingDirection,t,InputVariables="subjs",OutputVariableNames="PhaseEncodingDirection");
t = [t ph]
function ap = getPhaseEncodingDirection(subj)
%read AP json file
jsonText = fileread("/Volumes/myDirectory/" + subj + "/folder/Fieldmapap.json");
jsonData = jsondecode(jsonText);
ap = jsonData.PhaseEncodingDirection;
end
类别
在 帮助中心 和 File Exchange 中查找有关 JSON Format 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!