JSON to DF problem

I m working with a Rstudio code, i have 450 JSON files, i have all in my workspace, with some JSON files are all rigth, but with some files like this one (2.json - Google Drive , is a 296kb json) when i try to make the field tm to dataframe i have this mistake

Error in (function (..., row.names = NULL, check.rows = FALSE, check.names = TRUE, : arguments imply differing number of rows: 0, 1

The code that i use is

data = rjson::fromJSON(file = "2.json", simplify = T)
a = as.data.frame(data$tm)

With the files that are ok i obtain a 1 observation of x variables.

How can i avoid this priblem with some files?

Another posibility that i think is select the rows that i need

    candidatos = list(
"name",
"score",
"tot_sFieldGoalsMade",
"tot_sFieldGoalsAttempted",
"tot_sTwoPointersMade",
"tot_sTwoPointersAttempted",
"tot_sThreePointersMade",
"tot_sThreePointersAttempted",
"tot_sFreeThrowsMade",
"tot_sFreeThrowsAttempted",
"tot_sReboundsDefensive",
"tot_sReboundsOffensive",
"tot_sReboundsTotal",
"tot_sAssists",
"tot_sBlocks",
"tot_sTurnovers",
"tot_sFoulsPersonal",
"tot_sPointsInThePaint",
"tot_sPointsSecondChance",
"tot_sPointsFromTurnovers",
"tot_sBenchPoints",
"tot_sPointsFastBreak",
"tot_sSteals"
)

 ListColum<-map(candidatos, function(x){
    as.data.frame(data$tm$"2"$x)
     } )

But R give me a list of 23 DF with no elements

Thanks

For your file, I think the problem comes from data$tm$2$lds$sBlocks which is empty so can't be bound to the rest.

One way that can circumvent the problem is to use rbind:

a <- do.call(rbind, data)

It gives a warning but not an error. But I'm not sure if the format is the same as what you want.


The structure of the json file is quite complex, so if you're only interested in a few values that does seem like a good solution.

data$tm$"2"$x

This won't work: $ is only valid with a name, not with a variable containing the name. You need to use [[:

ListColum<-map(candidatos, function(x){
  as.data.frame(data$tm$"2"[[x]])
} )

The format is a big ugly though, map returns a list, and you put a data frame in each element. Also the names are meaningless. This will be better:

selected_values <- map_dfc(candidatos,
                           ~ data$tm$"2"[[.x]])
selected_values
names(selected_values) <- candidatos

Note that I changed the definition of candidatos to be a character vector rather than a list:

candidatos = c(
  "name",
  "score",
  "tot_sFieldGoalsMade",
   ...
)

Lists are a strange class and should only be used when the others are not possible.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.