Reading data from file with jsondecode

26 次查看(过去 30 天)
Hello everyone :)
I am struggling reading some data from a file using jsondecode function. I have the following data in a text file:
[0, [0,
3,
1,
['X3_5', 'X4_4', 'X4_5'],
[0, 0, 1],
[1,
[[1, [-41844328211318033252367, 344173910578922950492160]],
[0, [344173910578922950492160]],
[
[[0, [66782537082182499309963]],
4],
[[0, [-764979303944605824758909685951]],
19105490]
]]]]]:
Sometimes when I run
% path to text file
filePath = './myfile';
% Read the content of the file
fileID = fopen(filePath, 'r');
fileContent = fscanf(fileID, '%c');
fclose(fileID);
% Preprocess the content
fileContent = strrep(fileContent, '''', '"');
fileContent = strrep(fileContent, newline, '');
fileContent = strrep(fileContent, ':', '');
parsedStructure = jsondecode(fileContent);
I'm having two problems:
  1. A different value is stored, e.g., it saves -41844328211318034137088 instead -41844328211318033252367. How can I save the values in exact arithmetic?
  2. It ignores some brackets, e.g., the first list in [[0, [66782537082182499309963]],4] is merged as follows:
parsedStructure{2}{6}{2}{3}{1}{1}
0
6.6783e+22
parsedStructure{2}{6}{2}{3}{1}{2}
4
I have tried to solve the second problem using several nested if statements. However, I feel it is adding unnecesary complexity to the code and it just fails everytime it finds another similar situation. Any advice or suggestion is well received :)

回答(1 个)

Taylor
Taylor 2024-2-6
Have you tried readstruct? It will create a structure from JSON data, and you can even parse by selected standards.

产品


版本

R2022b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by