从R调用时,来自Google Directions API的格式错误的JSON

时间:2013-11-22 20:08:46

标签: json r google-api rcurl

这可能是重复的 - 但我找不到解决这个问题的方法。

我正在使用httpGET()来调用Google方向API。

的软件包:

require(RCurl)
require(rjson)
require(gooJSON)

代码是:

url = "http://maps.googleapis.com/maps/api/directions/json?origin=12.9673293,77.7173975&destination=12.9373613,77.700985&waypoints=optimize:true|12.9723379,77.7117611|12.9922162,77.715895|12.9629354,77.7122996&sensor=false"
routeJSON = httpGET(url= url)
routeList = fromJSON(routeJSON)

我明白了:

Error in fromJSON(routeJSON) : 
  unexpected escaped character '\]' at pos 18

我将JSON写入文件并将其复制到jsoneditoronline.com。我得到了:

Error: Parse error on line 51:
...         "points" : "qscnA_djyMj@kAT[\]\
-----------------------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[', got 'undefined'

validated by jsonlint

但是当我将URL放入浏览器并将输出复制到jsoneditoronline时它会起作用。

知道它为什么会发生和/或如何规避它?

编辑:我尝试过gooJSON,但它似乎不支持地图API V3。

> goomap(url)
$Status
$Status$code
[1] 610

$Status$request
[1] "geocode"

$Status$error_message
[1] "The Geocoding API v2 has been turned down on September 9th, 2013. The Geocoding API v3 should be used now. Learn more at https://developers.google.com/maps/documentation/geocoding/"

1 个答案:

答案 0 :(得分:1)

以下对我来说很好:

require(rjson)
url = "http://maps.googleapis.com/maps/api/directions/json?origin=12.9673293,77.7173975&destination=12.9373613,77.700985&waypoints=optimize:true|12.9723379,77.7117611|12.9922162,77.715895|12.9629354,77.7122996&sensor=false"
fromJSON(file=url)

但是,如果有无效的json数据,可以调用

fromJSON(url, unexpected.escape="keep")

将转义字符视为普通字符(例如\]变为])