function jsonstr = struct2json(a)
    //
    // Copyright 2015 Christian Klauer, klauer@control.tu-berlin.de, Licensed under BSD-License
    //
    // Rev 1 as of 4.3.15: Initial version
    // Rev 2 as of 4.3.15: added arrays of strings that are defined by e.g. list('str1', 'str2')
    // Rev 3 as of 17.3.15: added support for vectors
    //
    // Example usage:
    //
    // clear a;
    // a.Field1 = 2;
    // a.Field2 = "jkh";
    // a.Field3 = 1.2;
    // a.F3.name = "Joe";
    // a.F3.age = 32;
    // //a.F3.data = [1,2];
    // a.vector = [1,2,3,4.5];
    // jsonstr = struct2json(a);
    // disp(jsonstr);
    //    
    //     Warning: For strings make sure you escape the special characters that are used by the JSON-format!
    // 
    // Maybe the precision of float values can be adjusted by the command "format"
    //

    function valstr=val2str(val)
        select typeof(val)

        case "string"
            if length(length(val)) == 1 then
                valstr = '''' + string(val) + '''';
            end
            
        case "list" // convert to array of strings
            valstr = '[';
            
            N = length(val);
            for i=1:(N-1)
                valstr = valstr + '''' + string( val(i) ) + '''' + ',';
            end
            valstr = valstr + '''' + string( val(N) ) + '''' + ']';
            

        case "constant"
            if length(val) == 1 then
                valstr = string(val);
            else
//                valstr = '''' + "** Matrix not supported **" + '''';
                valstr = sci2exp(val(:)');
            end

        case "st"
            valstr = struct2json(val);

        else
            valstr = '''' + "**Datatype " + typeof(val) + " not supported **" + '''';
        end
    endfunction

    if isstruct(a) then
        F = fieldnames(a);
        str = "{ ";
        N = length(length(F));

        for i = 1:(N-1)
            f = F(i);
            val = eval('a.'+f);
            valstr = val2str(val);
            str = str + '''' + f + '''' + ' : ' + valstr + ' , ';
        end

        f = F(N);
        val = eval('a.'+f);
        valstr = val2str(val);
        str = str + '''' + f + '''' + ' : ' + valstr + ' } ';

    else
        error("Not a structure")
    end

    jsonstr = str;
endfunction



clear a;
a.Field1 = 2;
a.Field2 = "jkh";
a.Field3 = 1.2;
a.F3.name = "Joe";
a.F3.age = 32;
//a.strArray(1) = 'V1'
//a.strArray(2) =  'Xn';
a.strArray =  list( 'V1', 'Xn' );
a.vector = [1,2,3,4.5535894379345];

//a.F3.data = [1,2];
jsonstr = struct2json(a);
disp(jsonstr);




