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.

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, '}'];
end

Example output

{"MySimulinkModel/Manual Switch":0,"MySimulinkModel/Subsystem/Null switch":1}