【问题标题】:Ruby regular expression (regex) to get JSON data from databaseRuby 正则表达式 (regex) 从数据库中获取 JSON 数据
【发布时间】:2021-05-08 21:54:50
【问题描述】:

我想使用正则表达式从user_location 列中获取latlon,而在数据库中,列数据以JSON 格式存储为{"lon":74.46586,"lat":31.523199}。 我使用 split 方法获取值,这不是一个好习惯,如下所示。

lon = @session_request.user_location.split(',').first.split('=>').last.chomp('}').to_flat = @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"

获取值的正则表达式或任何更好的解决方案??

【问题讨论】:

标签: ruby-on-rails json ruby google-maps expression


【解决方案1】:

如果您使用带有 Jsonb 的 postgresql 不确定 json 是否会这样做,您可以轻松地进行以下操作。

location = @session_request.user_location

lon = 位置[“lon”] 纬度 = 位置[“纬度”]

I was tested on my database and rails by doing following

meta = table.metadata = {"lon":74.46586,"lat":31.523199}

puts meta["lon"]
74.46586

但如果你想让正则表达式做到这一点,你可以做以下。

lon, lan = location.scan(/(\d+\.\d+)/)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-17
    • 2012-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多