jeroen / jsonlite

A Robust, High Performance JSON Parser and Generator for R
http://arxiv.org/abs/1403.2805
Other
377 stars 40 forks source link

Parsing JSONP #52

Open sjackman opened 9 years ago

sjackman commented 9 years ago
fromJSON(RCurl::getURL("http://live.nhle.com/GameData/GCScoreboard/2014-11-10.jsonp"))
Error in parseJSON(txt) : lexical error: invalid char in json text.
                                       loadScoreboard({"games":[{"usna
                     (right here) ------^
sjackman commented 9 years ago

@BernhardKonrad I tried to use jsonlite::fromJSON with gameday.

jeroen commented 9 years ago

Yes, jsonp is not json. You should only use jsonp to avoid cross domain problems in the browser. Just use regular json in R.

sjackman commented 9 years ago

The API that I'm using (see the example above) unfortunately does not provide JSON, only JSONP. It would be a nice-to-have feature if parseJSON detected and removed the JSONP padding.

jeroen commented 9 years ago

Try something like this:

library(httr)
req <- GET("http://live.nhle.com/GameData/GCScoreboard/2014-11-10.jsonp")
jsonp <- content(req, "text")
json <- gsub('([a-zA-Z_0-9\\.]*\\()|(\\);?$)', "", jsonp, perl = TRUE)
data <- fromJSON(json)

Regex from here.

sjackman commented 9 years ago

Thanks for the workaround. Would you consider adding a fromJSONP function? It would be a nice convenience.

jeroen commented 9 years ago

I'll think about it, but it's a bit silly really. jsonp is just a hack for json to bypass the cross origin policy. It makes no sense outside of the browser. I can't think of why any API would provide jsonp but not json.

sjackman commented 9 years ago

Me neither. I agree it's dumb, but that's what I'm working with.