Skip to content

Commit e886486

Browse files
Handle struct array in m2json
1 parent ecd0a27 commit e886486

File tree

2 files changed

+16
-0
lines changed

2 files changed

+16
-0
lines changed

plotly/plotly_aux/Test_m2json.m

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,13 @@ function testStruct(tc)
101101
tc.verifyEqual(m2json(values), expected);
102102
end
103103

104+
function testStructArray(tc)
105+
values = struct("a", 1, "b", "text");
106+
values = [values values];
107+
expected = "[{""a"" : 1, ""b"" : ""text""}, {""a"" : 1, ""b"" : ""text""}]";
108+
tc.verifyEqual(m2json(values), expected);
109+
end
110+
104111
function testDatetime(tc)
105112
value = datetime("2023-05-01 12:30:45");
106113
expected = """2023-05-01 12:30:45""";

plotly/plotly_aux/struct2json.m

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,13 @@
11
function str = struct2json(s)
2+
if isscalar(s)
3+
str = oneStruct2json(s);
4+
else
5+
str = arrayfun(@oneStruct2json,s);
6+
str = sprintf("[%s]",strjoin(str,", "));
7+
end
8+
end
9+
10+
function str = oneStruct2json(s)
211
f = fieldnames(s);
312
strList = cellfun(@(x) sprintf('"%s" : %s', x, m2json(s.(x))), f, 'un', 0);
413
str = sprintf("{%s}", strjoin(strList, ", "));

0 commit comments

Comments
 (0)