Parse JSONP with R

一个人想着一个人 提交于 2019-12-03 22:48:50
jbaums

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!