json encode/decode
조회 수: 25 (최근 30일)
이전 댓글 표시
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.
답변 (1개)
Jan
2022년 5월 23일
편집: Jan
2022년 5월 23일
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.
참고 항목
카테고리
Help Center 및 File Exchange에서 JSON Format에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!