json encode/decode
7 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
I am trying to seriaze/deserialize a model using json but a run into problem. Basically my problem is that the json encoded 1xN arrays get decoded into Nx1 arrays which compactly can be reproduced like this
>> a = [1,2,3];
>> assert( isequal(a, jsondecode(jsonencode(a))))
Assertion failed.
This was quite unexpected to me. A more expanded version of the problem goes like this
>> a = [1,2,3]
a =
1 2 3
>> s = jsonencode(a)
s =
'[1,2,3]'
>> jsondecode(s)
ans =
1
2
3
What I want is this i.e. encode/decode is reversible something like this
>> jsondecode(s)
ans = [1,2,3]
Please bear with me as I am new to MatLab but I do not underderstand this behavior. Can anyone please elaborate on this and guide me to how to obtain the result that I want? I think this is the same issue as is raised here Vector dimesions are different before encoding json and after decoding json - (mathworks.com) but I would like to avoid traversing my nested data structure and transposing all arrays.
Réponses (1)
Jan
le 23 Mai 2022
Modifié(e) : Jan
le 23 Mai 2022
Does the encode of Matlab's production server help?
a = [1,2,3]
j1 = jsonencode(a)
a1 = jsondecode(j1)
j2 = mps.json.encode(a)
a2 = mps.json.decode(j2)
If mps is not available on your computer, store the data in a struct and use an ugly workaround:
S.a = [1,2,3];
S = IncludeSize(S);
j = jsonencode(S);
S2 = jsondecode(j);
S2 = RestoreSize(S2)
function S = IncludeSize(S)
F = fieldnames(S);
for k = 1:numel(F)
aF = F{k};
data = S.(F{k});
if isnumeric(data) % Maybe: && isrow(data)
S.size_.(aF) = size(data);
end
end
end
function S = RestoreSize(S)
F = fieldnames(S.size_);
for k = 1:numel(F)
aF = F{k};
siz = S.size_.(aF);
S.(aF) = reshape(S.(aF), siz(:).');
end
S = rmfield(S, 'size_');
end
What a pity that json does not save the dimensions exhaustively.
1 commentaire
Voir également
Catégories
En savoir plus sur JSON Format dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!