function output = getConfig(varargin) % Extract config parameters out of a json file. % % Output: Structure resulting from jsondecode() function. % % Inputs: % ("filename", filename) filename is the full path (with file extension) to % the json file to read. % Default: "config.json" % % ("convertTextToString", boolean) MATLAB jsondecode parser automatically % translate text to char arrays. This option replace these char arrays with % strings. % Default: true % % ("parameters", [parameter1, parameter2]) the output structure only contains % the parameters specified in the given string array/scalar. The default value % return all the parameters. % Default: "*" % % Example: % getConfig("filename", "simulationConfig.json",... % "convertTextToString", false,... % "parameters", ["simulationModel" "patientParameters"]); % % Tips: % getConfig("parameters", "foo") % is equivalent to % getConfig().foo options = inputParser; addOptional(options, "filename", "config.json"); addOptional(options, "convertTextToString", true); addOptional(options, "parameters", "*"); parse(options, varargin{:}); options = options.Results; config = jsondecode(fileread(options.filename)); if not(isequal(options.parameters, "*")) allParameters = string(fields(config))'; parametersToRemove = allParameters(not(ismember(allParameters, options.parameters))); config = rmfield(config, parametersToRemove); end if options.convertTextToString parameters = string(fields(config))'; for parameter = parameters if ischar(config.(parameter)) config.(parameter) = string(config.(parameter)); end if iscell(config.(parameter)) if all(cellfun(@ischar, config.(parameter))) config.(parameter) = string(config.(parameter))'; end end end end output = config; end