Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

How parse JSON formatted rows in a dataframe in R?

I have a data frame where each row contains JSON formatted input. How can I parse these 3 rows into one table. I tired following commands, but it shows error.

a<-data.frame(v1=c('[{"ID":1,"Type":"Honda","Key":{"Service":"Destan","Name":"John"},"Fields":{"Price":23.005,"Cost":10,"DIFF":"13.005"}}]',
                   '[{"ID":2,"Type":"BMW","UpdateType":"Every hour","Key":{"Service":"Destan","Name":"Mark"},"Fields":{"Price":2.005,"Cost":1,"DIFF":"1.005"}}]',
                   '[{"ID":1,"Type":"Honda","Key":{"Service":"Destan","Name":"John"},"Fields":{"Price":13.005,"Cost":4,"DIFF":"9.005"}}]'))
a<-paste0(a$v1, collapse = ",")
l <- fromJSON(paste0(a$v1, collapse = ","))

Error is Error in a$v1 : $ operator is invalid for atomic vectors


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you're trying to concat the rows of json into a larger valid json string, I think you'll also need surrounding [ and ]. Like:

missing_array_ends <- paste0(a$v1, collapse=',')
json_in_r <-  glue::glue("[{missing_array_ends}]") %>% fromJSON

But, I think another complication is the nested structure of the json. Key and Field have multiple sub entries. But you can flatten (unlist) them if you work on each row (lapply). lapply returns a list of items that you want to be rows in a dataframe. dplyr::bind_rows combines them back into a single dataframe

lapply(a$v1, function(j) unlist(fromJSON(j))) %>%
  bind_rows

creates

# A tibble: 3 x 8
  ID    Type  Key.Service Key.Name Fields.Price Fields.Cost Fields.DIFF
  <chr> <chr> <chr>       <chr>    <chr>        <chr>       <chr>      
1 1     Honda Destan      John     23.005       10          13.005     
2 2     BMW   Destan      Mark     2.005        1           1.005      
3 1     Honda Destan      John     13.005       4           9.005      
# … with 1 more variable: UpdateType <chr>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...