【发布时间】:2021-05-08 21:54:50
【问题描述】:
我想使用正则表达式从user_location 列中获取lat 和lon,而在数据库中,列数据以JSON 格式存储为{"lon":74.46586,"lat":31.523199}。
我使用 split 方法获取值,这不是一个好习惯,如下所示。
lon = @session_request.user_location.split(',').first.split('=>').last.chomp('}').to_f
和
lat = @session_request.user_location.split(',').last.split('=>').last.chomp('}').to_f
我想做上面代码的正则表达式。
从我的终端出现以下结果
pry(#)> 位置 = @session_request.user_location*
=> "{"lon"=>74.43935992994889, "lat"=>31.52203286189515}"
pry(#)> lon = location.split(',').first.split('=>').last.chomp('}')
=> "74.43935992994889"
pry(#)> lat = location.split(',').last.split('=>').last.chomp('}')
=> "31.52203286189515"
获取值的正则表达式或任何更好的解决方案??
【问题讨论】:
-
如果您使用的是 Postgres,那么有内置的查询 JSON 的方法,您不需要 Regex。见active_record_postgresql.html#json-and-jsonb
标签: ruby-on-rails json ruby google-maps expression