Matlab code to export all Simulink Manual Switch states as JSON
This MATLAB function iterates through all manual switches in the currently loaded Simulink model (gcs) and exports their switch state (0 or 1) to a JSON string.
The JSON is generated directly and not via struct() and jsonencode() since struct() does not support spaces or slashes in field names.
switch_positions_to_json.m
function jsonStr = switch_positions_to_json()
% Finds all Switches in the Simulink model
switches = find_system(gcs, 'BlockType', 'ManualSwitch');
% Initializes a JSON string with an opening curly brace
jsonStr = '{';
% Iterates through all switches
for i = 1:length(switches)
switchPath = switches{i};
switchPos = get_param(switchPath, 'sw');
% Adds key-value pair to the JSON string
if i > 1
jsonStr = [jsonStr, ','];
end
% Replace newlines in the switch path with escaped backslash + n
escapedSwitchPath = strrep(switchPath, newline, '\\n');
% Adds the key in quotes and the value
jsonStr = [jsonStr, '"', escapedSwitchPath, '":', switchPos];
end
% Closes the JSON string with a closing curly brace
jsonStr = [jsonStr, '}'];
endExample output
switch_positions_example.json
{"MySimulinkModel/Manual Switch":0,"MySimulinkModel/Subsystem/Null switch":1}Check out similar posts by category:
Matlab/Simulink
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow