-3

我有一个使用预测 API (forecast.io) 的项目,我正在使用forecast.io包装器与之交互。据我所知,api 只返回如下数据:

{"latitude":37.8267,"longitude":-122.423,"timezone":"America/Los_Angeles","offset":-7,"currently":{"time":1367169220,"summary":"多云" "icon":"部分阴天","precipIntensity":0,"temperature":59.45,"dewPoint":59.31,"windSpeed":4.38,"windBearing":281,"cloudCover":0.56,"湿度“:0.69”,“压力”:1017.24,“能见度”:9.82,“臭氧”:326.11},“分钟”:{“摘要”:“一小时多云。”,“图标”:“部分多云-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,"湿度":0.71,"压力":1017.28,"能见度":9.31,"臭氧":326.07},

现在,我想提取压力或可见性等信息来使用我的应用程序。由于似乎没有 API 调用来获取该信息,我觉得我需要对其进行整理。

现在,我如何编写一个正则表达式来匹配温度之类的东西,然后在它旁边的引号中获取信息?我想将特定信息从 APi 发送到我的应用程序中的变量。编辑:我发现正则表达式将是一个非常糟糕的主意。很棒的电话。

有人建议我可以尝试向前看,但也许我错过了一些从根本上更简单的解决方案。http://www.regular-expressions.info/lookaround.html概述了向我建议的技术。

编辑:正确地建议我将其解析为 JSON,并且表达式将是一个坏主意。我同意并已经实施了这一点。如果有人有任何创造性的建议,我仍然对使用 REGEX 实现这一点的方法感到好奇。

4

1 回答 1

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
...
于 2013-04-28T17:58:34.077 回答