Extracting Multiple Quoted Values from String in R

Viewed 18

I'm attempting to extract multiple quoted values from a string:

{  "What is your license plate number?": "FSD15a",  "What is the color of your car?": "Grey",  "What is the make AND model of your car?": "Hyundai Sonata",  "What are the last three digits of your zip code?": "043",  "What are the last three digits of your phone number?": "681"}

Specifically, I would like each of these values (e.g. What is your license plate number?, FSD15a, What is the make AND Model of your car, Hyundai Sonata, etc) to be new columns in the df and have used the following code before to extract just the numbers:

df %>% mutate(col1 = str_extract_all(Custom.Fields, "\\d+")) %>%
unnest_wider(c(col1)) %>%
set_names(c(names(df), str_c('col', seq_along(.)[-1])))

I cannot for the life of me figure out how to do this with quoted values. Any help you could provide would be incredibly appreciated!

1 Answers

It is easier using jsonlite

library(jsonlite)
as.data.frame(fromJSON(Custom.Fields), check.names = FALSE)

-output

What is your license plate number? What is the color of your car? What is the make AND model of your car?
1                             FSD15a                           Grey                          Hyundai Sonata
  What are the last three digits of your zip code? What are the last three digits of your phone number?
1                                              043                                                  681

If there are multiple entries, split between the }{ and then apply the fromJSON by looping

do.call(rbind.data.frame, lapply(strsplit(Custom.Fields, 
   "(?<=\\})\\s+(?=\\{)", perl = TRUE)[[1]], fromJSON))
What.is.your.license.plate.number. What.is.the.color.of.your.car. What.is.the.make.AND.model.of.your.car.
1                                N/A                            N/A                                     N/A
2                             ABC123                          Blue                        Toyota Highlander
  What.are.the.last.three.digits.of.your.zip.code. What.are.the.last.three.digits.of.your.phone.number.
1                                            30127                                                  389
2                                              083                                                  313

data

Custom.Fields <- '{  "What is your license plate number?": "FSD15a",  "What is the color of your car?": "Grey",  "What is the make AND model of your car?": "Hyundai Sonata",  "What are the last three digits of your zip code?": "043",  "What are the last three digits of your phone number?": "681"}
Related