在MATLAB中读取Json对象
代码:在MATLAB中读取Json对象,json,matlab,Json,Matlab,代码: 我想替换文件中的更新参数(Breite)。需要指导。如果使用R2016b或更高版本,可以使用将JSON数据转换为结构。然后,您可以修改所需的字段,更改值,并使用重新编码为json 如果数据在文件中,则在使用jsondecode clc fid = fopen('filename.json', 'r'); str = fread(fid,'*char').'; fclose(fid); J = jsondecode(str); J.Matlab_NX.n1.Geometriep
我想替换文件中的更新参数(Breite)。需要指导。如果使用R2016b或更高版本,可以使用将JSON数据转换为结构。然后,您可以修改所需的字段,更改值,并使用重新编码为json 如果数据在文件中,则在使用
jsondecode
clc
fid = fopen('filename.json', 'r');
str = fread(fid,'*char').';
fclose(fid);
J = jsondecode(str);
J.Matlab_NX.n1.Geometrieparameter.Breite = 3;
outputjson = jsonencode(J);
fileID = fopen('filename.json','w');
fwrite(fileID, outputjson);
fclose(fileID);
如果您使用的是旧版本的MATLAB,那么文件交换提交非常出色,还可以将数据转换为struct
值得注意的是,使用这两种方法中的任何一种,必须将字段名转换为空格、hypens等,因此可能无法像您预期的那样保留。从2014b起,您还可以使用内部函数
matlab.internal.webservices.fromJSON()
和matlab.internal.webservices.toJSON()
将JSON字符串转换为Matlab数据结构并返回JSON
然后,您的示例将是:
fid = fopen('filename.json', 'r');
str = fread(fid, '*char').';
fclose(fid);
J = jsondecode(str);
% Change the value
J.Matlab_NX.n1.Geometrieparameter.Breite = 3
fid = fopen('filename.json', 'r');
str = fread(fid, '*char').';
fclose(fid);
J = jsondecode(str);
% Change the value
J.Matlab_NX.n1.Geometrieparameter.Breite = 3
obj = matlab.internal.webservices.fromJSON( fileread( 'filename.json'));
obj.Matlab_NX.n1.Geometrieparameter.Breite = 3;
jsonStr = matlab.internal.webservices.toJSON( obj);
% write jsonStr to file if needed