diff --git a/+bids/+util/jsondecode.m b/+bids/+util/jsondecode.m index 832f1fba..f254bd24 100644 --- a/+bids/+util/jsondecode.m +++ b/+bids/+util/jsondecode.m @@ -33,20 +33,48 @@ ismember(exist('jsondecode', 'file'), [2 3]); % jsonstuff / Matlab-compatible implementation end + if ~exist(file, 'file') + msg = sprintf('Unable to read file ''%s'': file not found', file); + bids.internal.error_handling(mfilename(), 'FileNotFound', ... + msg, false); + end + if has_jsondecode - value = jsondecode(fileread(file)); + try + value = jsondecode(fileread(file)); + catch ME + warning_cannot_read_json(file); + rethrow(ME); + end % JSONio elseif exist('jsonread', 'file') == 3 - value = jsonread(file, varargin{:}); + try + value = jsonread(file, varargin{:}); + catch ME + warning_cannot_read_json(file); + rethrow(ME); + end % SPM12 elseif exist('spm_jsonread', 'file') == 3 - value = spm_jsonread(file, varargin{:}); + try + value = spm_jsonread(file, varargin{:}); + catch ME + warning_cannot_read_json(file); + rethrow(ME); + end else url = 'https://github.com/gllmflndn/JSONio'; error('JSON library required: install JSONio from: %s', url); + end end + +function warning_cannot_read_json(file) + msg = sprintf('Could not read file:\n%s', file); + bids.internal.error_handling(mfilename(), 'CannotReadJson', ... + msg, true, true); +end diff --git a/requirements.txt b/requirements.txt index 9445f2e7..59febca2 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,4 @@ -miss_hit==0.9.35 +miss_hit pre-commit jupyterlab octave_kernel diff --git a/tests/tests_utils/test_json_decode.m b/tests/tests_utils/test_json_decode.m new file mode 100644 index 00000000..4b151ec1 --- /dev/null +++ b/tests/tests_utils/test_json_decode.m @@ -0,0 +1,31 @@ +function test_suite = test_json_decode %#ok<*STOUT> + try % assignment of 'localfunctions' is necessary in Matlab >= 2016 + test_functions = localfunctions(); %#ok<*NASGU> + catch % no problem; early Matlab versions can use initTestSuite fine + end + initTestSuite; +end + +function test_json_decode_file_not_found() + + % write dummy faulty json + + filename = fullfile(temp_dir, 'foo.json'); + assertExceptionThrown(@() bids.util.jsondecode(filename), ... + 'jsondecode:FileNotFound'); + +end + +function test_json_decode_parse_error() + + % write dummy faulty json + + filename = fullfile(temp_dir, 'wrong.json'); + fid = fopen(filename, 'Wt'); + fprintf(fid, '{"foo": "bla"'); + fclose(fid); + + assertWarning(@() bids.util.jsondecode(filename), ... + 'jsondecode:CannotReadJson'); + +end