1

I have a data.frame which contains json data:

dat1 = data.frame(id = 001, name = "Mac", score = '{"math":5}', date = '{"date1":"2018-01-19","date2":"2018-01-20"}')
dat2 = data.frame(id = 002, name = "Eric", score = '{"math":7}', date = '{"date1":"2018-01-18","date2":"2018-01-20"}')
dat = rbind(dat1, dat2)

And I want to get the following data.frame:

#   id name   score.math     date.date1       date.date2
# 1  1  Mac       5          2018-01-19       2018-01-20
# 2  2 Eric       7          2018-01-18       2018-01-20

I want to use jsonlite::fromJSON first and rbind data then.

1
  • You can use regexec and regmatches to convert the date and score fields to the required object types. First, use data.table::rbindlist(list(dat1, dat2), use.names = T, fill = T) to get a combined data.table and then call the function on the two columns. Commented Jan 21, 2018 at 3:01

1 Answer 1

0

Here is one option with jsonlite

library(jsonlite)
data.frame(c(dat[1:2], unlist(lapply(dat[3:4], function(x) 
    fromJSON(paste0("[", paste(x,  collapse=",\n"), "]"))),
            recursive = FALSE)), stringsAsFactors = FALSE)
#  id name score.math date.date1 date.date2
#1  1  Mac          5 2018-01-19 2018-01-20
#2  2 Eric          7 2018-01-18 2018-01-20
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.