我有一个使用预测API(forecast.io)的项目,我正在使用forecast.io包装器与它进行交互。据我所知,api只返回这样的数据:
{"latitude":37.8267,"longitude":-122.423,"timezone":"America/Los_Angeles","offset":-7,"currently":{"time":1367169220,"summary":"Mostly Cloudy","icon":"partly-cloudy-day","precipIntensity":0,"temperature":59.45,"dewPoint":59.31,"windSpeed":4.38,"windBearing":281,"cloudCover":0.56,"humidity":0.69,"pressure":1017.24,"visibility":9.82,"ozone":326.11},"minutely":{"summary":"Mostly cloudy for the hour.","icon":"partly-cloudy-day","data":[{"time":1367169180,"precipIntensity":0},{"time":1367169240,"precipIntensity":0},{"time":1367169300,"precipIntensity":0},{"time":1367169360,"precipIntensity":0},{"precipIntensity":0,"temperature":58.39,"dewPoint":58.83,"windSpeed":4.23,"windBearing":278,"cloudCover":0.59,"humidity":0.71,"pressure":1017.28,"visibility":9.31,"ozone":326.07},
现在,我想提取压力或可见性等信息,以便使用我的应用。由于似乎没有API调用只是获取该信息,我觉得我需要解决它。
现在,我如何编写正则表达式以匹配温度等内容,然后获取旁边引号中的信息?我想从APi向我的应用程序中的变量发送特定信息。编辑:我发现一个正则表达式将是一个非常糟糕的主意。很棒的电话。
有人建议我可以尝试前瞻,但也许我错过了一些从根本上更简单的解决方案。 http://www.regular-expressions.info/lookaround.html概述了向我建议的技术。
编辑:正确地建议我将其解析为JSON,并且表达式将是一个坏主意。我同意并实施了这一点。如果有人有任何创意建议,我仍然很想知道如何通过REGEX实现这一目标。
答案 0 :(得分:1)
就我所知,您可以看到的格式是有效的JSON。您不应该使用正则表达式来解析JSON。使用JSON库。在红宝石中,一个是内置的。看来你真的想要:
require "json"
...
data = JSON.parse json_data # json_data is what the API service returns
temperature = data["currently"]["temperature"]
visibility = data["currently"]["visibility"]
pressure = data["currently"]["pressure"]
...
但是,您正在使用的forecast.io
包装器似乎为您执行了所有解析,并返回应该如此访问的对象:
require "forecast_io"
...
data = Forecast::IO.forecast ...
...
temperature = data.currently.temperature
visibility = data.currently.visibility
pressure = data.currently.pressure
...