1

I am trying to automate a JSON parsing in R (I had to remove the "https:// from the URLs because I don't have enough reputation points):

library(Quandl)
library(jsonlite)

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

for various numbers in page=X. The above code snippet executes properly. For that I am trying to use eval(parse()) but I am doing something wrong. So I have the following:

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)

BUT when I try to execute:

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

where n<-2 or any other integer then the console freezes with the following error messsage:

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

What am I doing wrong here?

Richard Erickson
  • 2,568
  • 8
  • 26
  • 39

1 Answers1

0

Have a read of the difference between paste and cat

cat will just print to the screen, it won't return anything. To create a string you should use paste or paste0.

For example, consider

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

Even when running concat <- cat(text1, n, text2), it prints the output to the console, and concat is empty/NULL

The solution is to use paste0 to create the string expression

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))))

Also, you don't need to use eval, you can use paste0 directly

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

koko <- fromJSON(paste0(text1, n), flatten=TRUE)
Community
  • 1
  • 1
SymbolixAU
  • 25,502
  • 4
  • 67
  • 139