How to extract the data from webread output?
25 次查看(过去 30 天)
显示 更早的评论
Could someone please help me with understanding how to extract the data from webread output?
The question is as follows:
I am loading the data from the server, and need to be able to ready it in Matlab as a table or mat file. The problem is that it is either a string from json code or a struct with many layers, and I do not quite understand how to extract variables that are linked together.
The code is a follows:
----
key = 'Q.N.DE.W2.S11.S13.N.A.LE.F4.T._Z.XDC._T.S.V.N._T'
url = [api 'data/QSA/' key];
options2 = weboptions('ContentType','text');
data2 = webread(url)%,options)
data1= webread(url,options2)
---
And I would like to be able to extract: these two linked variables:
<generic:ObsDimension value="2021-Q1"/>
<generic:ObsValue value="7854"/>
The first one-- as a string and the second one -- as a number.
0 个评论
采纳的回答
Ive J
2021-7-21
编辑:Ive J
2021-7-21
It's always better to first check the RESTful API documentations. In your case, you can get those values either by applying regexp to XML contents, or read/decode it in JSON format:
key = 'Q.N.DE.W2.S11.S13.N.A.LE.F4.T._Z.XDC._T.S.V.N._T';
api = 'https://sdw-wsrest.ecb.europa.eu/service/';
url = [api 'data/QSA/' key];
raw = webread(url);
data = jsondecode(raw);
% get ids/values
ObsDimension = {data.structure.dimensions.observation.values.id}.';
ObsValue = struct2table(data.dataSets.series.x0_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0.observations); % ObsValue are stored here
% create a new table from these 2 arrays
res = table(ObsDimension, ObsValue{1, :}.', 'VariableNames', {'ObsDimension', 'ObsValue'})
You could also use regexp:
key = 'Q.N.DE.W2.S11.S13.N.A.LE.F4.T._Z.XDC._T.S.V.N._T';
api = 'https://sdw-wsrest.ecb.europa.eu/service/';
url = [api 'data/QSA/' key];
opts = weboptions('ContentType', 'text');
raw = webread(url, opts);
ObsDimensionNew = regexp(raw, '(?<=<generic:ObsDimension value=")(.*?)[^"/>]*', 'match').';
ObsValueNew = regexp(raw, '(?<=<generic:ObsValue value=")(.*?)[^"/>]*', 'match').';
resNew = table(ObsDimensionNew, ObsValueNew, 'VariableNames', {'ObsDimension', 'ObsValue'})
3 个评论
Peter Perkins
2021-7-27
Even better, create a timetable, something like
>> ObsDimension = datetime(ObsDimension,'Format','uuuu-QQQ');
>> res = timetable(ObsValue{1, :}.', 'RowTimes',ObsDimension, 'VariableNames',{'ObsValue'});
>> head(res)
ans =
8×1 timetable
Time ObsValue
_______ ________
1999-Q1 0
1999-Q2 0
1999-Q3 0
1999-Q4 0
2000-Q1 991
2000-Q2 1042
2000-Q3 1093
2000-Q4 1143
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 JSON Format 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!