How to get jsondecode to preserve map keys (numerical keys are prefixed with 'x')
조회 수: 12 (최근 30일)
이전 댓글 표시
Hi,
Could someone explain why this happens:
jsonencode(jsondecode('{"a":"b"}'))
% '{"a":"b"}' (works as one would assume)
jsonencode(jsondecode('{"1":"b"}'))
% '{"x1":"b"}' (numeric value is previxed with 'x')
jsonencode(jsondecode('{"a.b":"b"}'))
% '{"a_b":"b"}' ('.' is converted to '_')
And how to work around it?
Some context:
I'm utilising a web api endpoint to post data, and it requires the data in similar format that in the second case above. But I'm not able to produce reliably the json payload (the example is a simplification of the actual problem)
Thanks
댓글 수: 0
채택된 답변
Jemima Pulipati
2020년 12월 23일
Hello,
From my understanding, you are using jsondecode() to decode an object and then used a jsonencode() to encode it back.
You are trying to decode a JSON object, which gets decoded in MATLAB as a MATLAB struct. A valid field name for struct can start only with letters and can contain letters, digits and underscores.
In this case, the field names ("1", "a.b") being provided are not valid field names for struct so makeValidName function modifies these field names and returns a valid field name when the object is used along with jsondecode(). This has been stated as a limitation for jsondecode() documentation. The makeValidName function constructs valid MATLAB identifiers from input strings, where the field names "1", "a.b" are modified to "x1", "a_b".
The expectation of jsondecode() function is a valid JSON object with valid field names (for struct) should be passed as input.
As a workaround, you may use the containers.Map which returns the map object from the inputs 'keySet' and 'valueSet'. In your case, the 'keySet ' could be the actual field name that you want to store and the struct value can be passed onto the 'valueSet' argument.
The following answer from the community might be of relevance to you:
추가 답변 (0개)
참고 항목
카테고리
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!