1

(update) An array of geocoordinates, built from a collection of records

[{"point_lon"=>0.1307336132e3, "point_lat"=>-0.252978933e2, "title"=>"kata tjuta"}, 
{"point_lon"=>0.154984876e3, "point_lat"=>-0.17e2, "title"=>"error case"}, 
{"point_lon"=>0.1310369614747e3, "point_lat"=>-0.253455545e2, "title"=>"uluru"}]

has proper quoting structure, but for JSON input to a javascript needs the rockets to be replaced by a colon.

Transforming the array via JSON.generate or to_json unfortunately leads to quoting of the decimal values and being ignored by the javascript

[{"point_lon":"130.7336132","point_lat":"-25.2978933","point_name":"kata tjuta"},
{"point_lon":"154.984876","point_lat":"-17.0","point_name":"error case"},
{"point_lon":"131.0369614747","point_lat":"-25.3455545","point_name":"uluru"}] 

How can this array be transformed without quoting decimals?

Jerome
  • 5,583
  • 3
  • 33
  • 76
  • Can't reproduce on `rails 5.1.6`, When I do `puts a.to_json` I get `[{"point_lon":130.7336132,"point_lat":-25.2978933,"title":"kata tjuta"},{"point_lon":154.984876,"point_lat":-17.0,"title":"error case"},{"point_lon":131.0369614747,"point_lat":-25.3455545,"title":"uluru"}]` – user000001 May 12 '19 at 14:34
  • Good point. I get the same result if I state the array as `a`... however that array is a collection `@points` and that collection to_json gets quoted. – Jerome May 12 '19 at 14:40
  • That's strange, it should work for collections too. Perhaps the fields don't have correct data type? Could you add the definition of the table from `schema.rb`? – user000001 May 12 '19 at 14:46
  • 1
    @user000001 yes, data types are decimal, with `, precision: 15, scale: 10` @Sebastian Palma same quoted output – Jerome May 12 '19 at 14:50

1 Answers1

2

This is because you use decimal numbers instead of float, so rails quotes the strings to preserve the precision. You can find methods to avoid this in this related question: Rails JSON Serialization of Decimal adds Quotes

user000001
  • 32,226
  • 12
  • 81
  • 108