【问题标题】:Eval parse for a JSONJSON 的 Eval 解析
【发布时间】:2016-03-23 20:07:09
【问题描述】:

我正在尝试在 R 中自动进行 JSON 解析(我不得不从 URL 中删除“https://,因为我没有足够的信誉点):

library(Quandl)
library(jsonlite)

tmp <- 
fromJSON("www.quandl.com/api/v3/datasets.json?database_code=WIKI&page=2",flatten = TRUE)

page=X 中的各种号码。上面的代码 sn -p 可以正常执行。为此,我尝试使用eval(parse()),但我做错了。所以我有以下内容:

text1 <- 'fromJSON("www.quandl.com/api/v3/datasets.json?database_code=WIKI&page='
text2 <- '",flatten = TRUE)'
and to verify that I create the string properly:
> text1
[1] "fromJSON(\www.quandl.com/api/v3/datasets.json?database_code=WIKI&page="
> text2
[1] "\",flatten = TRUE)"
> cat(text1,n,text2,sep="")
fromJSON("www.quandl.com/api/v3/datasets.json?database_code=WIKI&page=2",flatten = TRUE)

但是当我尝试执行时:

koko <- eval(parse(text = cat(text1,n,text2,sep="")))

如果n&lt;-2 或任何其他整数,则控制台会冻结并显示以下错误消息:

?
Error in parse(text = cat(text1, n, text2, sep = "")) : 
  <stdin>:1:4: unexpected '{'
1:  D_{
       ^ 

我在这里做错了什么?

【问题讨论】:

  • 顺便说一句,我尝试在 text1 和 text2 字符串周围同时使用 "" 和 '' 但这没有帮助。
  • cat 不会返回任何内容,我认为您应该改用paste0。见this answer
  • 为什么要使用eval(parse())

标签: json r parsing eval


【解决方案1】:

阅读the difference between paste and cat

cat 只会打印到屏幕上,不会返回任何内容。要创建字符串,您应该使用pastepaste0

例如,考虑

concat <- cat(text1, n, text2)
p <- paste0(text1, n, text2)

即使在运行concat &lt;- cat(text1, n, text2) 时,它也会将输出打印到控制台,并且concat 为空/NULL

解决方法是使用paste0创建字符串表达式

text1 <- 'fromJSON("http://www.quandl.com/api/v3/datasets.json?database_code=WIKI&page='
text2 <- '",flatten = TRUE)'
n <- 2
koko <- eval(parse(text = (paste0(text1, n, text2))))

另外,你不需要使用eval,你可以直接使用paste0

text1 <- 'http://www.quandl.com/api/v3/datasets.json?database_code=WIKI&page='
n <- 2

koko <- fromJSON(paste0(text1, n), flatten=TRUE)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-19
    • 2010-10-31
    • 1970-01-01
    • 2012-03-27
    • 1970-01-01
    • 2014-04-18
    相关资源
    最近更新 更多