0

I want to know if there is any way we can convert json strings to a list in a vectorized fashion, in other words, I want to know if we can use a list of json to convert into a list of lists in R.

There are many options to convert from Json to list. however, all of them only accept one json string at time.

I have following list of json format:

x =
c("{"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]}", 
{"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]})

Now I want to convert them to list. Right now I use the foreach package to convert them into list. The following is code is what I use:

library(jsonlite)
library(foreach)
library(doParallel)
registerDoParallel(cores = 2)

z <- foreach(i = 1:length(x), .combine = 'rbind') %dopar% { 
fromJSON(x[1])}

However, I want to do something like following:

z <- Vectroize_fromJSON(x)

Any ideas?

Note: The reason using foreach is that I have found it to be faster than a normal for loop. However, when the list of of json is large, then it becomes impractical.

Kush Patel
  • 3,685
  • 5
  • 42
  • 65

1 Answers1

4

Is this something close to what you want?

vectorize_fromJSON <- Vectorize(fromJSON)
z <- vectorize_fromJSON(x)
Psidom
  • 209,562
  • 33
  • 339
  • 356
  • Do you know how to assign just number when converting json to list in r? Currently it put json string as variable name in list – Kush Patel Apr 18 '16 at 18:36
  • It should not matter if the variable name is a string, since you can always extract the element by specifying the numeric index? For example, `li <- list(a = 3)` then `li[[1]] == li$a = 3` – Psidom Apr 19 '16 at 00:47