Code covered by the BSD License  

Highlights from
Coffee Roulette

image thumbnail

Coffee Roulette

by

 

13 Feb 2011 (Updated )

Let Matlab decide whose turn it is to get the coffee.

J=mat2json(M)
function J=mat2json(M)

%JSON2MAT converts a Matlab structure into a javscript data object (JSON).
%         M can also be a file name. In teh spirit of fast prototyping 
%         this function takes a very loose approach to data types and 
%         dimensionality - neither is explicitly retained.
%
%         The second input argument is optional and when used it indicates
%         the name of teh file where J is to be stored.
%
%Example: mat2json(json2mat('{lala:2,lele:4,lili:[1,2,{bubu:5}]}')) 
%
% Jonas Almeida, March 2010

switch class(M)
    case 'struct'
        if length(M) > 1
            J='[';
        else
            J = '';
        end
        for ii = 1:length(M)
            Jj='{';
            f=fieldnames(M(ii));
            for i=1:length(f)
                Jj=[Jj,'"',f{i},'":',mat2json(M(ii).(f{i})),','];
            end
            Jj(end)='}';
            J = [J Jj ','];
        end
        if length(M) > 1
            J(end)=']';
        else
            J=J(1:end-1);
        end
    case 'cell'
        J='[';
        for i=1:length(M)
            J=[J,mat2json(M{i}),','];
        end
        J(end)=']';
    case 'logical'
        if M
            J=['true'];
        else
            J=['false'];
        end
    otherwise
        if isnumeric(M) % notice looseness in not converting single numbers into arrays
            if length(M(:))==1
                J=num2str(M);
            else
                s=size(M);
                if (length(s)==2)&&(s(1)<2) % horizontal or null vector
                    J=['[',num2str(M),']']; % and of destroying dimensionality
                    J=regexprep(J,'\s+',',');
                elseif length(s)==2 %2D solution
                    J='[';
                    for i=1:s(1)
                        J=[J,mat2json(M(i,:)),','];
                    end
                    J(end)=']';
                elseif length(s)>2 % for now treat higher dimensions as linear vectors
                    J=['[',num2str(M(:)'),']']; % and of destroying dimensionality
                    J=regexprep(J,'\s+',',');
                end
            end
        else
            J=['"',regexprep(M,'%(?=[^%])','%%'),'"']; % otherwise it is treated as a string
        end
end

% if nargin>1 %save JSON result in file
%     fid=fopen(F,'w');
%     fprintf(fid,'%s',J);
%     fclose(fid);
% end

Contact us