forked from Future-Power-Networks/Simplus-Grid-Tool
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSaveAsJsonToFile.m
39 lines (35 loc) · 1.14 KB
/
SaveAsJsonToFile.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
%
% Saves a Matlab struct as a json file
%
% Author(s): Rob Oldaker
%
% Modified by Yitong Li:
% The option ['Pretty Print',true] in jsonencode is only available for
% matlab 2021a or later. Therefore, this setting is removed and replaced by
% a tedious manual method.
%
function SaveAsJsonToFile(data,fn)
% Check the matlab version
matlabVersion = version('-release');
matlabVersion = matlabVersion(1:(end-1));
matlabVersion= str2double(matlabVersion);
% Call jsonencode
if matlabVersion>=2021
json = jsonencode(data,'PrettyPrint',true,'ConvertInfAndNaN',false);
else
json = jsonencode(data,'ConvertInfAndNaN',false);
end
% Make the json file cleaner
json = strrep(json,'{','\n{\n');
json = strrep(json,'}','\n}\n');
json = strrep(json,'[','\n[\n');
json = strrep(json,']','\n]\n');
% NaN and Inf are *not* valid json literals so put them in quotes to make it valid json
json = strrep(json,'-Inf','"-Inf"');
json = strrep(json,'NaN','"NaN"');
json = strrep(json,'Inf','"Inf"');
%
fid = fopen(fn,'wt');
fprintf(fid, json, + '\n');
fclose(fid);
end