Why is my array of strings encoded as a single string with "jsonencode"?
8 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
MathWorks Support Team
am 2 Sep. 2022
Beantwortet: MathWorks Support Team
am 14 Sep. 2022
I created a struct with data:
>> data.key_a = "value_a";
>> data.key_b = ["value_b"];
Then, I encoded the struct in JSON format:
>> json = jsonencode(data);
The resulting JSON looks like this:
{"key_a":"value_a","key_b":"value_b"}
I would expect the attribute "key_b" to have a value ["value_b"] as I specified the field "key_b" to have an array of strings as its value in the "data" struct above. Why is this not the case?
Akzeptierte Antwort
MathWorks Support Team
am 6 Feb. 2023
This occurs because MATLAB doesn't make a distinction between a single (scalar) value and a 1x1 array. So, both values are encoded as JSON strings rather than JSON arrays containing a single string.
As a workaround, "key_b" could be stored as a cell array instead:
>> data.key_a = "value_a";
>> data.key_b = {"value_b"};
>> json = jsonencode(data);
This results in the desired JSON:
{"key_a":"value_a","key_b":["value_b"]}
0 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu JSON Format finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!