Access the data from a Struct

2 次查看(过去 30 天)
I have a struct with fields
val = struct with fields:
abstract: [1×1 struct]
body_text: [72×1 struct]
when I extract the text data in body_text using "val.body_text.text" I got 72*1 struct. But when I try "A = val.abstract.text", I got only the first struct of the 72 structs. How can I put all these [72×1 struct] into A?
Thanks!
  3 个评论
Ameer Hamza
Ameer Hamza 2020-3-30
''so val.abstract.text is either invalid reference or is the name of the 1x1 struct under val.abstract'''
Not necessarily. For example
>> s.text = '123';
s.xyz = 2;
val.abstract = s;
val.body_text = repmat(s, 1, 72);
>> val
val =
struct with fields:
abstract: [1×1 struct]
body_text: [1×72 struct]
>> val.abstract.text
ans =
'123'
Susan
Susan 2020-3-30
Sorry for the confusion! What I meant was "But when I try "A = val.body_text.text", I got only the first struct of the 72 structs"

请先登录,再进行评论。

采纳的回答

Ameer Hamza
Ameer Hamza 2020-3-30
编辑:Ameer Hamza 2020-3-30
Try this, if the data in the field 'text' is scalar
A = [val.abstract.text];
If it is vector than try
A = {val.abstract.text};
  5 个评论
Ameer Hamza
Ameer Hamza 2020-3-31
Try the following code. Place it one directly above the JSON files, or you can modify the first line according to the path of your JSON files. It will read all files, and gather their abstract.text and body_text.text fields into one struct. It then writes the final struct as a JSON file.
files = dir('JSON files/*.json');
s = struct('abstract', [], 'body_text', []);
for i=1:numel(files)
filename = fullfile(files(i).folder, files(i).name);
data = jsondecode(fileread(filename));
if ~isempty(data.abstract)
s.abstract = [s.abstract; cell2struct({data.abstract.text}, 'text', 1)];
end
if ~isempty(data.body_text)
s.body_text = [s.body_text; cell2struct({data.body_text.text}, 'text', 1)];
end
end
str = jsonencode(s);
f = fopen('filename.json', 'w');
fprintf(f, '%s', str);
fclose(f);
Susan
Susan 2020-3-31
Thank you so much! I really appreciate your help.

请先登录,再进行评论。

更多回答(0 个)

Community Treasure Hunt

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

Start Hunting!

Translated by