JSON 的评估分析

Eval parse for a JSON

我正在尝试在 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 中的各种数字。上面的代码片段正确执行。为此,我正在尝试使用 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<-2 或任何其他整数然后控制台冻结并显示以下错误消息:

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

我做错了什么?

阅读 the difference between paste and cat

cat 只会打印到屏幕上,它不会 return 任何东西。要创建字符串,您应该使用 pastepaste0.

例如,考虑

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

即使在运行concat <- cat(text1, n, text2)时,它也会将输出打印到控制台,而concat是empty/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)