Parse JSONP with R

丶灬走出姿态 提交于 2019-12-05 07:12:41

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/9455437/parse-jsonp-with-r

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