How to force jsonencode to return floating format

조회 수: 12 (최근 30일)
Pete sherer
Pete sherer 2023년 6월 15일
답변: Rik 2023년 6월 15일
Hi,
Is there a way to use jsonencode to force some varialble to be floating format, rather than integer?
apiData = struct;
apiData.job_name= "job_rollup: PT BP Creation";
apiData.as_at_date= '2023-05-01';
apiData.DR= 1.000;
string( jsonencode( apiData, 'PrettyPrint', true))
returns
ans =
"{
"job_name": "job_rollup: PT BP Creation",
"ncores": 32,
"as_at_date": "2023-05-01",
"DR": 1
}"
I want the DR to be 1.0, so other API can recognize that it is float and not integer.
Thanks,

답변 (2개)

Aakash
Aakash 2023년 6월 15일
Use the sprintf function to format the value of DR to a string with one decimal place
So change the required line to: apiData.DR = sprintf('%.1f', 1);

Rik
Rik 2023년 6월 15일
Unfortunately, as you can see in the documentation, customizing the conversion is not really possible this way.
You will either have to adjust the output from jsonencode, or you will have to write your own implementation. Writing your own implementation is not that difficult, especially if you control the input and can therefore implement all paths your code needs to take.
I have written such an implementation, but I will not share it here, precisely because it only does what I need it to do. Once I have written a larger test suite, I may post it on the FileExchange, just like I did with my alternative to jsondecode: JSON. Given the name of this submission I might add the encoder to this submission. If you want to get notified if and when that happens, feel free to click the follow button there.

카테고리

Help CenterFile Exchange에서 JSON Format에 대해 자세히 알아보기

태그

제품


릴리스

R2022a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by