jcarlos jcarlos - 2 months ago 23
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
},\n
\"start_location\" : {\n
\"lat\" : -3.0831712,\n


\"polyline\" : {\n \"points\"
:
\"b}yQ`iqmJFD@@?@@@?@?@?@?B?@?@CXAPAJATCZ?@?@?@?@@@?
@@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

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)


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


1

Thanks

Answer

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

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

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.

Comments