1

Building on my previous question here, can R parse JSONP objects? I have successfully been using RJSONIO to read/parse JSON objects from the web.

I encountered a feed that is JSONP. When I attempted to use fromJSON(), an empty list is returned.

Any help will be very much appreciated. Staying within R is preferred. Thanks in advance.

Community
  • 1
  • 1
Btibert3
  • 38,798
  • 44
  • 129
  • 168

1 Answers1

3

To parse JSONP content, you can strip away the function call that is wrapped around the JSON content (as described here in the context of PHP), and then parse the content as you would for standard JSON.

To do this in R, try something along the lines of:

j  <- readLines('http://live.nhl.com/GameData/20112012/2011020908/Roster.jsonp')
j <- sub('[^\\{]*', '', j) # remove function name and opening parenthesis
j <- sub('\\)$', '', j) # remove closing parenthesis
library(RJSONIO)
res <- fromJSON(j)

# example output:
unlist(lapply(res$data$home$skaters$player, function(x) x$lname))
 [1] "Greene"       "Zubrus"       "Parise"       "Ponikarovsky"
 [5] "Henrique"     "Sykora"       "Josefson"     "Kovalchuk"   
 [9] "Bernier"      "Carter"       "Harrold"      "Clarkson"    
[13] "Salvador"     "Janssen"      "Elias"        "Volchenkov"  
[17] "Fayne"        "Taormina" 

I'm not that familiar with JSON, nor JSONP, so I'm not sure if it's possible to encounter JSONP content with multiple function call wrappers. If so, you'll need to modify the sub pattern somewhat. If you'd like to point me to your JSONP feed, I can amend this solution accordingly. RJSONIO might also offer easier ways to extract list elements than lapply.

Community
  • 1
  • 1
jbaums
  • 27,115
  • 5
  • 79
  • 119