Retrieve data from textfile

I am trying to retrieve data from this text file. Ultimately, I want to get the information for date (e.g.6/9/2016) and absolute time (e.g. 20.000761) using Matlab. How do I do that?
Here is an example:
{"metadata":{"date":"6/9/2016 4:25:43 PM","TotalShrooms":{"AbsoluteTime":20.000761,"Value":0}},"hits":{},"recording":false}
Thank you.

Answers (1)

dpb
dpb on 30 Aug 2017
Edited: dpb on 30 Aug 2017
fmt=['{"metadata":{"date":"' '{%{M/d/yyyy hh:mm:ss a}D' '","TotalShrooms":{"AbsoluteTime": %f %*[^\n]'];
% file open preamble code goes here to get valid file handle fid
data=textscan(fid,fmt);
will return cell array containing the datetime and value data variables.
UPDATE: Fixup of parens mismatch...

4 Comments

Yik Ka Yau
Yik Ka Yau on 30 Aug 2017
Edited: Yik Ka Yau on 30 Aug 2017
Hello! Thank you for your generous help.
I tried the code but it said there is an error.
I think this is the code (written below) that has an error. I tried to look over it but not sure what went wrong.
fmt=['{"metadata":{"date":"' {'%{M/d/yyyy hh:mm:ss a'}D' ","TotalShrooms":{"AbsoluteTime":' %f %*[^\n]'];
textscan cannot handle spaces in a date format unless 'whitespace' has been set to exclude space. That might actually work out in the given example -- however if there are any other spaces on the line then it would fail. For example if it were "AbsoluteTime": 20.000761 instead of "AbsoluteTime":20.000761 then setting the 'whitespace' to exclude space would lead to failure in the later space.
I tried what you said and it worked.
However, when I typed data=textscan(fid,fmt), it said error using textscan. Invalid file identifier. Use fopen to generate a valid file identifier.
You need to use
fid = fopen('NameOfTextFileGoesHere', 'rt');

Sign in to comment.

Tags

Asked:

on 30 Aug 2017

Commented:

on 5 Sep 2017

Community Treasure Hunt

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

Start Hunting!