jcarlos jcarlos - 1 year ago 124
JSON Question

How to escape backslash just in some parts of a string - R

I'm trying to use jsonlite to flatten the results from google maps directions api.

The results are in json format and they have some sections like these here:

\"polyline\" : {\n \"points\"
: \"xdyQtaqmJb@Ab@?|@AfBAtA?l@At@@D?F?D?\"\n
\"start_location\" : {\n
\"lat\" : -3.0831712,\n

\"polyline\" : {\n \"points\"
@@B@@@?@@@@@?@?@?@?bBH\"\n },\n
\"start_location\" : {\n

in most of then I have "\" inside the coding for points which in turn makes jsonlite to crash with the error

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

I need some directions on how to double escape \ just inside the pair of double quotes after
\"points\" : \

Here the code I use to get the json output


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

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

Well, I still don't have an easy answer to flatten this output to a data frame, but with the examples from this post [A biased comparsion of JSON packages in R] I've got to retrive the output with
RJSONIO::fromJSON(jsonOutput,unexpected.escape = "keep")



Answer Source

If you're using Google Maps API then my googleway package handles this for you


## 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)
#         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

Alternatively, if you want to do this yourself, you're better off using the jsonlite package: jsonlite::fromJSON(your_url) to read the JSON directly.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download