MATLAB: How to convert csv file containing MAC addresses to JSON array

json

I have multiple csv files with a long list of MAC addresses and RSS (Received signal strength) values, as shown below.
34:a8:4e:fd:3c:50, -53
b0:7f:b9:bc:f0:e0, -61
b0:7f:b9:bc:f1:01, -82
34:a8:4e:fc:13:53, -58
b0:7f:b9:bc:f0:42, -79
34:a8:4e:fd:3c:53, -53
I need to convert these csv files in to JSON arrays in the format below:
"wifi":{ "34:a8:4e:fd:3c:50":-53,
"b0:7f:b9:bc:f0:e0":-61,
"b0:7f:b9:bc:f1:01":-82,
"34:a8:4e:fc:13:53":-58,
"b0:7f:b9:bc:f0:42":-79,
"34:a8:4e:fd:3c:53":-53,
… }
Currently I am trying to enter the values as a struct but MATLAB tells me MAC addresses that have ':' or start with a number, are not appropriate field names. Is there a way around this? Or can anyone suggest a way of converting the files?

Best Answer

I'm assuming you want to use jsonencode to do the encoding. To be honest, considering the simplicity of your output, you could simply encode it yourself.
Using jsonencode you will have to store your data in a map instead of a structure:
wifidata = readtable('20190108_113507_WifiSensor(1).csv', 'Delimiter', ','); %or however you're reading your input file

wifidata = containers.Map(wifidata{:, 1}, wifidata{:, 2}); %convert to a map
json = jsonencode(struct('wifi', wifidata)) %convert map to json
Bypassing jsonencode entirely:
wifidata = readtable('20190108_113507_WifiSensor(1).csv', 'Delimiter', ','); %or however you're reading your input file
json = compose('{"wifi":{%s}}', strjoin(compose('"%s":%d', string(wifidata{:, 1}), wifidata{:, 2}), ','))
Either way, note that matlab will not be able to read that json back with mangling the mac addresses as jsondecode does not have an option to read the json in map. It's unfortunately a limitation of matlab that I complained about a long time ago.
Related Question