I'm parsing a JSON using the RJSONIO package.
The parsed item contains nested lists.
Each item in the list can be extracted using something like this:
dat_raw$`12`[[31]]
which correctly returns the string stored at this location (in this example, the '12'
refers to the month and [[31]]
to day).
"31-12-2021"
I now want to run a for
loop to sequentially extract the date for every month. Something like this:
for (m in 1:12) {
print(dat_raw$m[[31]])
}
This, naturally, returns a NULL
because there is no $m[[31]]
in the list.
Instead, I'd like to extract the objects stored at $`1`[[31]]
, $`2`[[31]]
, ... $`12`[[31]]
.
There must be a relatively easy solution here but I haven't managed to crack it. I'd value some help. Thanks.
EDIT: I've added a screenshot of the list structure I'm trying to extract. The actual JSON object is quite large for a dput()
output. Hope this helps
So, to get the date in this list, I'd use something like dat_raw$data$`1`[[1]]$date$gregorian$date
.
What I'm trying to do is run a loop to extract multiple items of the list by cycling through $data$`1`[[1]]$...
, $data$`2`[[1]]$...
... $data$`12`[[1]]$...
using $data$m[[1]]$...
in a for
loop where m
is the month.
Instead of dat_raw$`12`[[31]]
, you can have dat_raw[[12]][[31]]
if 12
is the 12th element of the JSON. So your for
loop would be:
for (m in 1:12) {
print(dat_raw[[m]][[31]])
}