json char with too many decimals, need removal

I got some json str = '{"hund": 0.3253533250000000000000000000000000, "kat": "dfsdfs", "baenkebider": 0.002021203321320000000000000000000000}';
In reality its a longer string with even more figures. I need to remove all those long decimals. 7-8 decimals is enough, so I end up with something like:
str = '{"hund": 0.3253533, "kat": "dfsdfs", "baenkebider": 0.0020212}';
If someone can help with an elegant solution I will appreciate it a lot!
Thanks in advance,
-best
mergh

3 Comments

>> split(extractBetween(str,'{','}'),',')
ans =
3×1 cell array
{'"hund": 0.3253533250000000000000000000000000' }
{' "kat": "dfsdfs"' }
{' "baenkebider": 0.002021203321320000000000000000000000'}
>> str2double(extractAfter(ans,':'))
ans =
0.3254
NaN
0.0020
>>
Use join() to put the isfinite pieces back together.
Alternatively, although it is crude, you could just do a string subsitution for some arbitrary number of consecutive zeros with empty or simply pick up the leftmost N characters of the numeric values.
A regular expressions maven could undoubtedly write a very clever pattern, but that isn't me... :)
Thanks for answering. join() and isfinite() is however a bit messy with regards to the cell piece.
I knew Stephen or similar would be along...
You'll note I specifically did NOT say it was elegant... :)

Sign in to comment.

 Accepted Answer

str = '{"hund": 0.3253533250000000000000000000000000, "kat": "dfsdfs", "baenkebider": 0.002021203321320000000000000000000000}';
Method one (truncate to 9 characters):
out = regexprep(str,'\d+\.\d+','${$&(1:9)}')
out = '{"hund": 0.3253533, "kat": "dfsdfs", "baenkebider": 0.0020212}'
Method two (seven fractional digits):
fun = @(s)sprintf('%.7f',sscanf(s,'%f'));
out = regexprep(str,'\d+\.\d+','${fun($&)}')
out = '{"hund": 0.3253533, "kat": "dfsdfs", "baenkebider": 0.0020212}'

2 Comments

This will of course not work on an arbitrary JSON string, so you need to be careful if you want to do so. You could consider using a custom JSON encoder that allows you to trim trailing 0 in decimal notation.

Sign in to comment.

More Answers (0)

Products

Release

R2020b

Asked:

on 29 May 2021

Commented:

Rik
on 31 May 2021

Community Treasure Hunt

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

Start Hunting!