Search code examples
jsonrdataframenested-loopsrjson

Error in Parsing Json to Dataframe R


I am getting below mentioned error while passing Json dataframe.

Error in data.frame(Addr = "London", companyName = "Eagle SUITS",  : 
  arguments imply differing number of rows: 1, 0, 2 In addition: Warning message:
In data.frame(Addr = "NA", companyName = "SAMTEK ENTERPRISES",  :
  row names were found from a short variable and have been discarded

my data frame:

view(df_1)

json_data                id
{Data in json format}    123
{Data in json format}    456
{Data in json format}    789

I am using below mentioned code:

library(jsonlite)
json_dfs <- mapply(f, df_1$json_data, df_1$id, SIMPLIFY = FALSE)

The JSON file content from OP: view(df_1$json_data)


Solution

  • The issue seems to be in function f which is used to transform json data and merge ID with JSON. The JSON data is nested data, hence it would be better to append as part of list created after parsing json and then convert it to desired format.

    I suggest to modify function as:

    f_JSON_Transform <- function(json, id){ 
      # transform json to list 
      tmp <- jsonlite::fromJSON(json) 
      # Append ID in list 
      tmp <- c(tmp, ID = id)
      # return 
      return(tmp) 
    }
    # Below call works without any error
    json_lists <- mapply(f_JSON_Transform, df1$json_data, df1$id, SIMPLIFY = FALSE)
    
    #Result
    #Output is too long to write here...but it is like
    #$test.txt$agreementOfficeAddr
    #[1] "NA"
    
    #$test.txt$companyName
    #[1] "SAMTEK ENTERPRISES"
    
    #$test.txt$companyAddress
    #[1] "E-524,GALI NO- 45, NEAR CHAND MASJID,SHASTRI PARK"
    #......
    #......