TrueBlue TrueBlue - 2 months ago 7
JSON Question

Compound Replace of Floating Point Number with Double Quotes

I have a problem with JSON strings flowing back and forth between PHP and javascript Ajax calls. The PHP routines are sending JSON encoded strings without quotes around the floating point numbers, i.e.

{"Route_1":[{"lat":-31.526107395574975,"lng":146.31591796875},{"lat":-31.51674215813217,"lng":145.5303955078125}]}}


But when the JSON string is received by the ajax routine, all the floating point numbers have double quotes around them as shown here:

{"Route_1":[{"lat":"-31.526107395574975","lng":"146.31591796875"},{"lat":"-31.51674215813217","lng":"145.5303955078125"}]}


So after a couple of days trying to get to the bottom of it, I have decided the best course of action is just to parse this to remove the double quotes. I can identify the floating point numbers and using .replace and callback. but the compound replace is not working as I would expect it to - that is it is just returning the same string.

Can anyone shed some light on this please? btw this is not the same issue as asking how to parse a JSON string.



var str = '{"Route_1":[{"lat":"-31.526107395574975","lng":"146.31591796875"},{"lat":"-31.51674215813217","lng":"145.5303955078125"}]}'

var regex = /[-+]?[0-9]*\.?[0-9]+/g;

var t = str.replace(regex, function(x) {
return x.replace(/"/g, "");
})

console.log(t);




Answer

You would need to match " as well in the regex. Check below update.

var str = '{"Route_1":[{"lat":"-31.526107395574975","lng":"146.31591796875"},{"lat":"-31.51674215813217","lng":"145.5303955078125"}]}';

var regex = /\"[-+]?[0-9]*\.?[0-9]+\"/g;

var t = str.replace(regex, function(x) {
  return x.replace(/"/g, "");
})

console.log(t);

Comments