필터 지우기
필터 지우기

Read in json file as three dimensional array

조회 수: 20 (최근 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 CenterFile Exchange에서 JSON Format에 대해 자세히 알아보기

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by