Read in json file as three dimensional array

10 ビュー (過去 30 日間)
Benedikt Krauß
Benedikt Krauß 2020 年 11 月 11 日
コメント済み: Nitesh Panchal 2021 年 4 月 26 日
Hello,
I have trouble with Matlab and reading data from JSON files. I basically have one .json file which looks like this:
{
"Data": {
"1": [
0.0,
0.1,
0.2,
0.3,
0.4,
0.5,
0.6,
0.7,
0.8,
0.9,
1.0
],
"2": [
3.1517,
3.4879332128,
3.551222604,
3.5870886304,
3.6319243674,
3.6911242439,
3.7654878049,
3.8551335026,
3.960078832,
4.0803263235,
4.2158762895
],
"3": [
3.4262,
3.5204004756,
3.5719092392,
3.6113550565,
3.6542077094,
3.7082794455,
3.777514335,
3.8639024635,
3.9684468861,
4.0916520841,
4.2337707085
]
}
}
Then in my Matlab code I try to read this data with:
fname = 'test.json';
fid = fopen(fname);
raw = fread(fid,inf);
str = char(raw');
fclose(fid);
jsonData = jsondecode(str);
Sadly all the data is then in a single dimensional array but I would need each data tab as one array, so that later on I can use it as "jsonData.("1")".
Where is the error in my code? Still at the beginning of using Matlab as you can probably guess my looking at my question.

回答 (1 件)

Eshaan Shah
Eshaan Shah 2020 年 11 月 11 日
編集済み: Eshaan Shah 2020 年 11 月 11 日
Hi,
I executed the following code in MATLAB 19b and it seems to work as expected.
fname = 'test.json';
fid = fopen(fname);
raw = fread(fid,inf);
str = char(raw');
fclose(fid);
jsonData = jsondecode(str);
Below is the content of jsonData:
>> jsonData
jsonData =
struct with fields:
Data: [1×1 struct]
>> jsonData.Data
ans =
struct with fields:
x1: [11×1 double]
x2: [11×1 double]
x3: [11×1 double]
In order to correctly access the individual arrays, you can execute
jsonData.Data.x1
jsonData.Data.x2
jsonData.Data.x3
Note: I see the same behavior in 19a, 19b, 20a, and 20b.
  1 件のコメント
Nitesh Panchal
Nitesh Panchal 2021 年 4 月 26 日
>> fname = 'test.m';
>> fid = fopen(fname);
>> raw = fread(fid,inf);
>> str = char(raw');
>> fclose(fid);
>> jsonData = jsondecode(str);
>> jsonData
jsonData =
struct with fields:
Data: [1×1 struct]
>> jsonData.Data
ans =
struct with fields:
x1: [11×1 double]
x2: [11×1 double]
x3: [11×1 double]
>> jsonData.Data,x1
ans =
struct with fields:
x1: [11×1 double]
x2: [11×1 double]
x3: [11×1 double]
Undefined function or variable 'x1'.
>> jsonData.Data.x1
ans =
0
0.1000
0.2000
0.3000
0.4000
0.5000
0.6000
0.7000
0.8000
0.9000
1.0000
>>

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeJSON Format についてさらに検索

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by