用R解析JSONP [英] Parse JSONP with R

查看:103
本文介绍了用R解析JSONP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我之前的问题此处的基础上,R可以解析JSONP对象吗?我已经成功地使用RJSONIO从网络读取/解​​析JSON对象.

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.

我遇到了一个JSONP提要.当我尝试使用fromJSON()时,将返回一个空列表.

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

任何帮助将不胜感激.首选停留在R之内.预先感谢.

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

推荐答案

要解析JSONP内容,您可以剥离包装在JSON内容周围的函数调用(如

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.

要在R中执行此操作,请尝试以下方法:

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" 

我对JSON和JSONP不太熟悉,所以我不确定是否可以通过多个函数调用包装器来遇到JSONP内容.如果是这样,您将需要稍微修改sub模式.如果您想指出我的JSONP供稿,我可以相应地修改此解决方案.与lapply相比,RJSONIO可能还提供了更简单的方法来提取列表元素.

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.

这篇关于用R解析JSONP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆