Clear Filters
Clear Filters

Read in json file as three dimensional array

20 views (last 30 days)
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.

Answers (1)

Eshaan Shah
Eshaan Shah on 11 Nov 2020
Edited: Eshaan Shah on 11 Nov 2020
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 Comment
Nitesh Panchal
Nitesh Panchal on 26 Apr 2021
>> 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
>>

Sign in to comment.

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!