1

I have the following data.frame with one column called "json" and two rows of JSON data:

df <- data.frame(json = c('{"client":"ABC Company","totalUSD":7110.0000,"durationDays":731,"familySize":4,"assignmentType":"Long Term","homeLocation":"Australia","hostLocation":"United States","serviceName":"Service ABC","homeLocationGeoLat":-25.274398,"homeLocationGeoLng":133.775136,"hostLocationGeoLat":37.09024,"hostLocationGeoLng":-95.712891}', '{"client":"ABC Company","totalUSD":7110.0000,"durationDays":731,"familySize":4,"assignmentType":"Long Term","homeLocation":"Australia","hostLocation":"United States","serviceName":"Service XYZ","homeLocationGeoLat":-25.274398,"homeLocationGeoLng":133.775136,"hostLocationGeoLat":37.09024,"hostLocationGeoLng":-95.712891}'))

I am trying to parse the JSON into a data.frame using fromJSON from the rjson package.

I cast the column as character type and then attempt to parse:

> df$json <- as.character(df$json)
> final <- fromJSON(json_str = df$json)

However, it only seems to give me the first row of JSON, whereas I expect 2 rows.

How can I parse the JSON into a data.frame from df$json?

1 Answer 1

7

You probably want a resultant data frame from this exercise, so:

do.call(rbind.data.frame, lapply(df$json, rjson::fromJSON))

##         client totalUSD durationDays familySize assignmentType homeLocation  hostLocation serviceName homeLocationGeoLat
## 2  ABC Company     7110          731          4      Long Term    Australia United States Service ABC           -25.2744
## 21 ABC Company     7110          731          4      Long Term    Australia United States Service XYZ           -25.2744
##    homeLocationGeoLng hostLocationGeoLat hostLocationGeoLng
## 2            133.7751           37.09024          -95.71289
## 21           133.7751           37.09024          -95.71289

The exact same results will come from:

do.call(rbind.data.frame, lapply(df$json, jsonlite::fromJSON))
do.call(rbind.data.frame, lapply(df$json, RJSONIO::fromJSON))
Sign up to request clarification or add additional context in comments.

5 Comments

Error in loadNamespace(name) : there is no package called ‘rjson’
Well, did you install it?
Just writing library(rjson) didn't work. install.packages('rjson') now it worked. Thanks :)
I think you may need to study up on both R and SO etiquette a bit.
Yes! I am trying hard :))

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.