Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON parse Number as String

What is best way to parse JSON number as String in javascript

Example:
{
  "a": 10.00
}

Notice I do not have control over value 10.00. I cannot add there "+''". I want to keep the decimal places, but it is not rule that there have to be 2 decimals.

Result should be 10.00 not 10

like image 612
hybaken Avatar asked Oct 17 '25 14:10

hybaken


2 Answers

If you need exactly the same number of decimals, the only way is if the JSON present the value as string. If you have no control over the source, you could edit the JSON before parsing, adding the quotes, but that could bring several problems. This needs to be tested toroughly.

json = '{ "a": 10.00, "b":2.1020, "d":0.20,"c": "21" }';

json = json.replace(/:\s*[^"0-9.]*([0-9.]+)/g, ':"$1"');

console.log(json);
console.log(JSON.parse(json));
like image 134
ariel Avatar answered Oct 20 '25 13:10

ariel


You can use JSON.parse with a reviver argument

const json = '{"a":{"b":0.1}}'

const data = JSON.parse(json, (_key, value, data) => typeof value === 'number' ? data.source : value)

console.log(data);
like image 27
Sam Denty Avatar answered Oct 20 '25 13:10

Sam Denty