2016-09-07 57 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