matlab 阅读json文件时出现语法错误“附加文本”

aurhwmvo  于 2023-08-06  发布在  Matlab
关注(0)|答案(1)|浏览(126)

我尝试使用以下脚本从MATLAB中的Arduino板读取json文件:

fileName = 'test1.json';            % filename in JSON extension 
str = fileread(fileName);           % dedicated for reading files as text 
data = jsondecode(str);             % Using the jsondecode function to parse JSON from string

字符串
但我得到了以下错误:
使用jsondecode JSON语法错误时出错,第1行,第79列(字符79):附加文本。read_json(line 4)data = jsondecode(str); %使用jsondecode函数从字符串解析JSON
我想一定是有引号,逗号或括号的...
我需要提取加速度值以便稍后在MATLAB中使用它们(acc_x、acc_y和acc_z)
json文件是:

{"acc_x": 0.24, "acc_y": 0.78, "acc_z": 0.46, "Timestamp": 1691078254.4053023},
{"acc_x": 0.27, "acc_y": 0.78, "acc_z": 0.47, "Timestamp": 1691078254.4153075},
{"acc_x": 0.29, "acc_y": 0.78, "acc_z": 0.5, "Timestamp": 1691078254.43097},
{"gy_x": -35.89, "gy_y": 3.78, "gy_z": 14.4, "Timestamp": 1691078254.43097},
{"acc_x": 0.32, "acc_y": 0.78, "acc_z": 0.47, "Timestamp": 1691078254.4409742},
{"gy_x": -33.39, "gy_y": 2.62, "gy_z": 13.98, "Timestamp": 1691078254.4409742},
{"acc_x": 0.32, "acc_y": 0.78, "acc_z": 0.44, "Timestamp": 1691078254.4409742},
{"gy_x": -29.79, "gy_y": 1.83, "gy_z": 8.79, "Timestamp": 1691078254.4409742},
{"acc_x": 0.27, "acc_y": 0.8, "acc_z": 0.41, "Timestamp": 1691078254.456637},
{"gy_x": -25.57, "gy_y": -0.37, "gy_z": 7.51, "Timestamp": 1691078254.456637},
{"acc_x": 0.25, "acc_y": 0.82, "acc_z": 0.44, "Timestamp": 1691078254.4666882},
{"gy_x": -25.57, "gy_y": -1.65, "gy_z": 8.85, "Timestamp": 1691078254.4767776},
{"acc_x": 0.22, "acc_y": 0.82, "acc_z": 0.46, "Timestamp": 1691078254.4767776},
{"gy_x": -28.81, "gy_y": -0.31, "gy_z": 11.29, "Timestamp": 1691078254.4767776},
{"acc_x": 0.23, "acc_y": 0.82, "acc_z": 0.46, "Timestamp": 1691078254.486785},

vlf7wbxs

vlf7wbxs1#

作为自包含的JSON文件,这是无效的,您需要两件事

  • 删除结尾的逗号,解析器将期望列表在此点之后继续
  • 看起来你有一个数组,需要用[] Package

因此,如果您的示例在str中,则需要类似于

str = regexprep( str, ',+$', '' );    % Remove trailing comma(s)
data = jsondecode( ['[', str, ']'] ); % Wrap array with square brackets

字符串
这适用于所述的示例,但您可能想弄清楚为什么您似乎只有一部分有效的json摘录存储在文件中,因为这可能只是症状的补丁,而不是解决导致此错误的根本原因。

相关问题