Matlab, jQuery and JSON

I do all my numerical algorithm development in Matlab, so I needed a way to easily get results from Matlab into javascript. Here is a (a pretty cool if I don’t say so myself) matlab code that creates a JSON file from a matlab data structure.


data.x = rand(10,1);
data.y = rand(10,1)

dataname = 'data' 

fid = fopen('matlab.json','w');

numdata = max(size(fieldnames(eval(dataname))))

fdata = char(fieldnames(eval(dataname)));

fprintf(fid,'{ "%s" : {\n ',dataname)
for dataiter=1:numdata,
  fprintf(fid,' "%s" : [ \n',fdata(dataiter));
  stmp = sprintf('%s.%s',dataname,fdata(dataiter));
  for i=1:(max(length(eval(stmp))))-1,
    stmp = sprintf('%s.%s(%i)',dataname,fdata(dataiter),i);
    fprintf(fid,'%1.10e , \n',eval(stmp));
  end
  stmp2 =  sprintf('%s.%s',dataname,fdata(dataiter));;
  stmp = sprintf('%s.%s(%i)',dataname,fdata(dataiter),(max(length(eval(stmp2)))));
  fprintf(fid,'%1.10e  \n',eval(stmp));

  if dataiter == numdata ,
    fprintf(fid,'] \n');
  else
    fprintf(fid,'], \n');
  end

end

fprintf(fid,'} } \n');

And then reading it in and parsing it with jQuery is really simple.


 var x = [];
 var y = [];
 $.ajaxSetup({ async: false});
  $.getJSON("matlab.json", function (json)
            {
              x = json.data.x.slice(0);
              y = json.data.y.slice(0);
            }
            );