0
votes

I am trying to come to the point where I create a graph on a given data that I am supposed to read from a text file.
So I use in my code fopen to open the text file, textscan to scan it, than make a string out of it and by using split I want to cut of the first part of every line and use the second part so that I can decode it into json and then use the information.
So my text file consists of two lines of information:

123456.99 :: working completed: result=0 , data ="{"day":"monday", "breakfast":"sandwich"}" 123456.99 :: working completed: result=0 , data ="{"day":"tuesday", "breakfast":"bread"}"

The first part of my code:

fileID  = fopen('test1');
text = textscan(fileID, '%s', 'delimiter','\n','whitespace','');
strLog = string(text{1});
res = split(strLog, "data =");
json_str = res(:, 2)  

And as a result I get a 2x1 string array. Output:

json_str =

2×1 string array

""{"day":"monday", "breakfast":"sandwich"}""
""{"day":"tuesday", "breakfast":"bread"}""

This is where I got stuck.
My first idea was to call cellfun and apply jsondecode. But I got

Error using jsondecode JSON syntax error at line 1, column 4 (character 4): extra text.

But it makes no sence to me, since that should be the " from "day" which for json should be okay!?

1

1 Answers

0
votes

In json_str you have quote marks " at the start and end. These need to be removed for jsondecode to work. For example J = jsondecode(json_str{1}(2:end-1)).

You can then use cellfun to process all elements. For example,

S = cellfun(@(x)jsondecode(x(2:end-1)),json_str)