Converting JSON to CSV in Rstudio with UTF coding

41 views Asked by At

I am trying to convert the following JSON text taken from this URL: https://dackkms.gov.in/Account/API/kKMS_QueryData.aspx?StateCD=01&DistrictCd=0108&Month=1&Year=2024

library(plyr)
library(RJSONIO)
c <- file('data.json', "r")
df  <- ldply(fromJSON(c), data.frame)
close(c)

This code gives me 13 observations and 998 variables. However, I should be getting 13 variables and 998 observations. Alternatively, I have tried:

df1 <- fromJSON("data.json")
my_dataframe <- do.call(data.frame, df1)

This gives me 11 observations and 998 variables. When I transpose this, I get a matrix and when I convert that matrix to a data frame, I get 1 observation and 3 variables. Any suggestions would be really helpful.

1

There are 1 answers

0
jamespryor On

Use fromJSON() of the jsonlite library:

library(jsonlite)

# JSON path/ URL:
path <- 'https://dackkms.gov.in/Account/API/kKMS_QueryData.aspx?StateCD=01&DistrictCd=0108&Month=1&Year=2024'

# read remote JSON:
json <- fromJSON(path)

# access 'data':
data <- json$data

# save 'data' as CSV:
data |>
  write.csv('./file-path-goes-here.csv', row.names = F)