Home > Enterprise >  Extracting Multiple Quoted Values from String in R
Extracting Multiple Quoted Values from String in R

Time:05-31

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!

CodePudding user response:

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

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"}
  •  Tags:  
  • r
  • Related