【问题标题】:lexical error: inside a string, '\' occurs before a character / Using jsonlite in R词法错误:在字符串中,“\”出现在字符之前/在 R 中使用 jsonlite
【发布时间】:2017-08-20 18:28:32
【问题描述】:

最近,如果我尝试解析来自 Google 的 JSON 响应,则会收到此错误。

lexical error: inside a string, '\' occurs before a character which it may not.
      [SICGCMCIAG?KAQ@I@KBKBGDGDOJ]\IHGDMDI@K@E?IAGAGAICGEGEIGIMOS
                 (right here) ------^

在浏览器中查看的由 google 发送的字符串看起来像这样(我缩短了它):

[SICGCMCIAG?KAQ@I@KBKBGDGDOJ]\\IHGDMDI@K@E?

这是我正在使用的代码

route_doc <- getURL(route)
route_response <- fromJSON(route_doc)

不知何故 jsonlite 挂在这里。 我该怎么做才能解析来自谷歌的响应?

经过一番调查: 如果折线条目包含反斜杠字符,则会发生此崩溃

"polyline" : {
                    "points" : "qv{uHwlni@R?"
                 },

谢谢!

更新:我正在使用此代码从 google 获取 JSON 响应:

route_from="Köln"
route_to="Hamburg"

get_route_url<-function(origin,
destination,
avoid,mode,
alternatives,
key, 
return.call = "json")

{
  root<-"https://maps.googleapis.com/maps/api/directions/" 
  u<-paste(root, 
           return.call, 
           "?origin=", origin,
           "&destination=",destination,
           "&avoid=",avoid, 
           "&mode=", mode,
           "&alternatives=",alternatives,
           "&key=",key, 
           sep = "") 
  return(URLencode(u))
  }


route<-get_route_url(route_from,
                     route_to,
                     "highways",
                     "driving",
                     "true",MYKEY)

route_doc <- getURL(route)

route_response <- fromJSON(route_doc)

还有一个错误,例如折线:

lexical error: inside a string, '\' occurs before a character which it may not.
          uHiani@@L@HBHBHBDDFDBDB`@@t@@\G"                      },    
                     (right here) ------^

【问题讨论】:

  • 使用library(googleway); google_directions(...) 或library(ggmap); route(...)
  • 如果其他解决方案不起作用,我会的。我想自己构建对 google api 的调用。所以这个崩溃总是发生在“折线”条目上。
  • 您可以发布您用来从 Google 获取响应的代码吗?
  • @SymbolixAU:我用我正在使用的代码更新了问题。

标签: json r google-maps jsonlite


【解决方案1】:

Google 的 API 以 JSON 格式返回响应,因此您实际上不需要使用 getURL 获取“文档”,因为 fromJSON 可以直接读取 JSON

所以只需在您的 route 对象上调用 fromJSON

route_response <- fromJSON(route)

并查看路线

library(googleway)
mapKey <- 'my_map_key'

df <- data.frame(polyline = route_response$routes$overview_polyline$points)

google_map(key = mapKey) %>%
  add_polylines(data = df, polyline = "polyline")

【讨论】:

    猜你喜欢
    • 2015-11-14
    • 2022-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-04
    • 2019-11-20
    • 1970-01-01
    相关资源
    最近更新 更多