How to force jsonencode to return floating format
9 次查看(过去 30 天)
显示 更早的评论
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,
0 个评论
回答(2 个)
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);
0 个评论
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.
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!