G Warner
G Warner

Reputation: 1369

Create JSON from Matlab

I have a workspace with a bunch of variables I'd like to turn into a JSON document using JSONlab. My code so far looks like this:

loadjason = {'{"Duration":Duration,"Num_Samples":nsamples,"Frequency":Freq,"Num_Channels":nchannels1}')

The items not in double quotes (i.e. Freq) are variables from my MATLAB workspace but my output is:

Error using loadjson>error_pos (line 482)
JSONparser:invalidFormat: Value expected at position 13:
{"Duration":<error>Duration,"Num_Samples

Error in loadjson>parse_value (line 471)
   error_pos('Value expected at position %d');

Error in loadjson>parse_object (line 206)
   val = parse_value(varargin{:});

Error in loadjson (line 96)
   data{jsoncount} = parse_object(opt);`

How do I pass variables into loadjson so that they are read as their values and not as literals?

Upvotes: 0

Views: 1151

Answers (1)

Dan
Dan

Reputation: 93

loadjason = {'{"Duration":Duration,"Num_Samples":nsamples,"Frequency":Freq,"Num_Channels":nchannels1}')

is not valid JSON. String values, such as Duration, need to be in quotes if they are strings (e.g., '"Duration":"5 seconds"'). Numeric values don't need quotes. E.g., '"Duration":5' is valid. Also your outermost brackets don't match, and you don't need { } enclosing the entire string twice. Modify your MATLAB code to produce something like this,

loadjason = '{"Duration":5,"Num_Samples":1,"Frequency":1,"Num_Channels":1}'

To take int values:

loadjason = '{"Duration":'
temp = int2str(Duration)
loadjason = strcat(loadjason,temp)

loadjason = '{"Num_Samples":'
temp = int2str(nsamples)
loadjason = strcat(loadjason,temp)

loadjason += ',{"Frequency":'
temp = int2str(freq)
loadjason = strcat(loadjason,temp)

loadjason += ',{"Num_Channels":'
temp = int2str(nchannels1)
loadjason = strcat(loadjason,temp)

loadjason += '}'

and continue for the rest of the variables. Alternately you could create a function that does this for you.

Upvotes: 2

Related Questions