Skip to content

Commit 95282d6

Browse files
Improve m2json; Support strings, datetime and convert -Inf to 'null', not '-null'
1 parent 3337a38 commit 95282d6

File tree

2 files changed

+34
-4
lines changed

2 files changed

+34
-4
lines changed

plotly/plotly_aux/m2json.m

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
elseif length(val) == 0
2323
valstr = '[]';
2424
end
25+
valstr = strrep(valstr,'-Inf', 'null');
2526
valstr = strrep(valstr, 'Inf', 'null');
2627
valstr = strrep(valstr, 'NaN', 'null');
2728
elseif ischar(val)
@@ -39,6 +40,12 @@
3940
else
4041
valstr = 'false';
4142
end
43+
elseif isdatetime(val)
44+
valstr = m2json(convertDate(val));
45+
elseif isstring(val)
46+
fh = ifel(isscalar(val),@char,@cellstr);
47+
valstr = m2json(fh(val));
4248
else
4349
valstr = ''; % wtf is it?
50+
warning("Failed to m2json encode class of type: %s",class(val));
4451
end
Lines changed: 27 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,27 @@
1-
function convertedDate = convertDate(date)
2-
date.Format = 'yyyy-MM-dd HH:mm:ss';
3-
convertedDate = char(date);
4-
end
1+
function output = convertDate(date)
2+
date = convertToDateTime(date);
3+
if isDate(date)
4+
format = "yyyy-mm-dd";
5+
else
6+
format = "yyyy-mm-dd HH:MM:ss";
7+
end
8+
output = string(date, format);
9+
end
10+
11+
function dt = convertToDateTime(input)
12+
if isdatetime(input)
13+
return
14+
elseif isnumeric(input)
15+
% Assume input is a datenum
16+
dt = datetime(input, 'ConvertFrom', 'datenum');
17+
elseif ischar(input) || isstring(input)
18+
% Assume input is a date string
19+
dt = datetime(input);
20+
else
21+
error('Unsupported date type');
22+
end
23+
end
24+
25+
function tf = isDate(dt)
26+
tf = all([hour(dt), minute(dt), second(dt)] == 0);
27+
end

0 commit comments

Comments
 (0)