Export labels and values labeled SPSS data into Json

Viewed 123

I have a large labelled SPSS file, it has about 800 variables and contains all metadata , label , value , variable. I am looking for a way to write it as json formt without losing the variable txt, label and value.

Here a sample dummy data:

library(haven)
library(labelled)

df <- data.frame(
  a = labelled(c(1, 1, 2, 3), labels = c(No = 1, Yes = 2)),
  b = labelled(c(1, 1, 2, 3), labels = c(No = 1, Yes = 2, DK = 3)),
  c = labelled(c(1, 1, 2, 2), labels = c(No = 1, Yes = 2, DK = 3)),
  d = labelled(c("a", "a", "b", "c"), labels = c(No = "a", Yes = "b")),
  e = labelled_spss(
    c(1, 9, 1, 2), 
    labels = c(No = 1, Yes = 2),
    na_values = 9  ))

df1 <- df %>% 
  set_variable_labels( a = "txt1- Do you use xxx?") %>% 
  set_variable_labels( b = "txt2-Do you use xxx?") %>% 
  set_variable_labels( c = "txt3-Do you use xxx?") %>% 
  set_variable_labels( d = "txt4-Do you use xxx?") %>% 
  set_variable_labels( e = "txt5-Do you use xxx?")  

If I used

jsonlite::write_json()

I can export the file as a json but I will lose label and other metadata. Is there any way to export it with metadata variable labels, value labels etc. to json file

library(jsonlite)
exportJSON <- toJSON(df1)
write_json(exportJSON, "output.json")
1 Answers

serializeJSON() allows for the conversion of R objects to JSON keeping intact all data and attributes (but excluding environments). The data can be restored with unserializeJSON().

library(labelled)
library(jsonlite)
library(tibble) 

df1 <- df1 %>%
  as_tibble() # For prettier printing of labels

# Write json file
write(serializeJSON(df1), file = "dat.json")

# Restore
unserializeJSON(readLines("dat.json"))

# A tibble: 4 x 5
          a         b         c d                 e
* <dbl+lbl> <dbl+lbl> <dbl+lbl> <chr+lbl> <dbl+lbl>
1   1 [No]    1 [No]    1 [No]  a [No]      1 [No] 
2   1 [No]    1 [No]    1 [No]  a [No]      9 (NA) 
3   2 [Yes]   2 [Yes]   2 [Yes] b [Yes]     1 [No] 
4   3         3 [DK]    2 [Yes] c           2 [Yes]
Related