1

I have a string that I convert to an array:

var data = "[[1, 2, 3,], [3, 2, 1]]";
var array = JSON.parse(data.replace(/,\s*]/g, ']'));

I need to be able to handle floating points, i.e input of this form:

var data = "[[2.,23.,1.5904], [4.,23,1.6208]]";

Using the browser console, when I try to do:

var ar = JSON.parse(data.replace(/,\s*]/g, ']'));

I get this error:

SyntaxError: JSON.parse: unterminated fractional number at line 1 column 5 of the JSON data

I guess it has something to do with the regexp of the JSON.parse(), but I am not strong in regexp yet, so I don't have a clue.

I have played around with this: https://regexone.com/ which actually helped understanding pretty much, but I'm still not able to fix my problem.

This question is kind of an extension to my previous question (which is solved):

Convert string of array, with array of array(s)

What I didn't think of at the time, was that I also need to be able to handle floating points

Community
  • 1
  • 1
MOR_SNOW
  • 787
  • 1
  • 5
  • 16

2 Answers2

2

You can quickly fix this with

data.replace(/\.,/g, ".0,)

This replaces every ., in 2., to 2.0,

Or you can do

data.replace(/\.,/g, ",")

Which removes the dots before the commas.

Bálint
  • 4,009
  • 2
  • 16
  • 27
2

The problem is that JSON needs a number after a dot.

The correct JSON will be this way:

var data = "[[2.0,23.0,1.5904], [4.0,23,1.6208]]";

So you must either output full float numbers (if you have control over the output) or parse the string to append zeroes to all dots, like this:

data.replace(/\.,/g, ".0,").replace(/\.]/g, ".0]");

Note that we need to also look for dots near ], not only commas.

Jorge Fuentes González
  • 11,568
  • 4
  • 44
  • 64