2016-09-07 72 views
2

我正在尝试使用jsonlite将Google Maps方向API的结果弄平。如何在字符串的某些部分逃避反斜杠 - R

的结果是JSON格式,他们有这样的这里的一些章节:

\"polyline\" : {\n      \"points\" 
: \"[email protected]@?|@[email protected]@@D?F?D?\"\n   
      },\n      
\"start_location\" : {\n      
\"lat\" : -3.0831712,\n 


\"polyline\" : {\n      \"points\" 
: 
\"b}yQ`[email protected]@[email protected]@@[email protected][email protected][email protected][email protected][email protected][email protected][email protected][email protected][email protected]@@? 
@@[email protected]@@[email protected]@@@@[email protected][email protected][email protected]?bBH\"\n      },\n 
        \"start_location\" : {\n  
在大多数然后

我有“\”的编码点,这反过来又使jsonlite与错误崩溃内

> fromJSON(out) 
Error: lexical error: inside a string, '\' occurs before a character which it may not. 
       "points" : "rsuQnzomJhBD\@lAF"      }, 
        (right here) ------^ 

我需要如何后\"points\" : \

下面的代码我加倍逃逸\只是一对双引号内的一些方向用于获取JSON输出

origin="-3.06010901,-60.04375624" 
    destination="-3.0876276,-60.06031519" 
    mode="walking" 
    units="metric" 
    language="en-EN" 

    baseURL <- "https://maps.googleapis.com/maps/api/directions/json?" 
    callURL <- paste0(baseURL,"origin=", origin, 
          "&destination=", destination, 
          "&units=", tolower(units), 
          "&mode=", tolower(mode), 
          "&language=",language) 

    tmout=10 
    opts = RCurl::curlOptions(connecttimeout=tmout) 
    out <- RCurl::getURL(callURL, .opts = opts) 

嗯,我还没有一个简单的答案来拉平这个输出到数据帧,但是从这篇文章[JSON包在R的一种有偏comparsion]实例我有如果您在使用谷歌地图API与RJSONIO::fromJSON(jsonOutput,unexpected.escape = "keep")

1

感谢

+0

难道你不能以类似的方式阅读此[对此](http://stackoverflow.com/questions/24183007/is-it-possible-to-read-geojson-or-topojson-file-in- R到平局-A-等值线图)? –

+0

@RomanLuštrik不幸的不是。 json输出只是将这些多段线编码为一个字段,您需要稍后对其进行解码,然后才能到达坐标。此json不是空间数据文件。我尝试了那里提出的解决方案,但没有奏效。谢谢。 – jcarlos

+0

'dput(out)'将有助于重现错误。由于很难从头创建一个糟糕的字符串。 – Tensibai

回答

2

以检索输出,然后我googleway包为您处理此

library(googleway) 

## your valid Google API key 
key <- read.dcf("~/Documents/.googleAPI", fields = "GOOGLE_API_KEY") 

directions <- google_directions(origin = "Melbourne International Airport, Melbourne, Austrlia", 
           destination = "MCG, Melbourne, Australia", 
           key = key) 

## and to decode the polyline: 
df_route <- decode_pl(directions$routes$overview_polyline$points) 
head(df_route) 
#   lat  lon 
# 1 -37.67477 144.8494 
# 2 -37.67473 144.8494 
# 3 -37.67417 144.8493 
# 4 -37.67411 144.8493 
# 5 -37.67409 144.8494 
# 6 -37.67409 144.8495 

另外,如果你想这样做你自己,你最好使用jsonlite包:jsonlite::fromJSON(your_url)直接读取JSON。

+0

谢谢,但我必须解码overview_polyline $分,因为我试图将谷歌地图API的指示输出平铺到数据框中。和jsonlite给出的错误显示在问题“fromJSON(出) 错误:词法错误:在一个字符串,”。显然它不处理“意外的扫描序列”,但RJSONIO确实如此。 – jcarlos

+1

@jcarlos尝试'jsonlite :: fromJSON(callUrl)' – Tensibai

+0

@Tensibai伟大的,这种方式,直接,它的工作原理。 – jcarlos