Home > front end >  How to join 2 fields in 1 in JSON with Ruby on Rails
How to join 2 fields in 1 in JSON with Ruby on Rails

Time:05-10

So i have this code in a JSON:

[ {
  "idema" : "0009X",
  "lon" : 0.963335,
  "fint" : "2022-05-03T13:00:00",
  "prec" : 0.0,
  "alt" : 406.0,
  "vmax" : 5.8,
  "vv" : 2.2,
  "dv" : 102.0,
  "lat" : 41.213894,
}}

And I want to get the fields lat and long and merge them like this in the JOSN:

  "longlat": "POINT(23.0 33.0)",

I'm parsing the file like this btw:

      meteo_station_list = JSON.parse(File.read('meteo_stations.json'))
      meteo_station_list.each do |station|
      MeteoStationAemet.create(station.to_h)

Thanks!

CodePudding user response:

1- You need to Convert this Json to Hash

meteo_station_list = JSON.parse(File.read('meteo_stations.json')).with_indifferent_access

2- you just need to loop through the hash and use this snippet

def genrate_point 
  meteo_station_list.each do |station|
    station[:longlat] = "point(#{station[:lat]} #{station[:lon]}"
    station.except!(:lat,:lon)
  end
end

check official except documentation

  • Related