1

I have two objects of the same type in JSON:

json <- '[{"client":"ABC Company","totalUSD":1870.0000,"durationDays":365,"familySize":4,"assignmentType":"Long Term","homeLocation":"Chicago, IL","hostLocation":"Lyon, France","serviceName":"Service ABC","homeLocationGeoLat":41.8781136,"homeLocationGeoLng":-87.6297982,"hostLocationGeoLat":45.764043,"hostLocationGeoLng":4.835659},{"client":"ABC Company","totalUSD":21082.0000,"durationDays":365,"familySize":4,"assignmentType":"Long Term","homeLocation":"Chicago, IL","hostLocation":"Lyon, France","serviceName":"Service ABC","homeLocationGeoLat":41.8781136,"homeLocationGeoLng":-87.6297982,"hostLocationGeoLat":45.764043,"hostLocationGeoLng":4.835659}]'

How can I parse both objects unto the same data.frame such that I have two rows that share the same columns?

To put that another way, I have a list of JSON objects that I am trying to parse into a data.frame.

I have tried this:

p <- rjson::newJSONParser()
p$addData(json)
df <- p$getObject()

This seems to return a list whereas I am wanting a data.frame:

> df
[[1]]
[[1]]$client
[1] "ABC Company"

[[1]]$totalUSD
[1] 1870

[[1]]$durationDays
[1] 365

[[1]]$familySize
[1] 4

[[1]]$assignmentType
[1] "Long Term"

[[1]]$homeLocation
[1] "Chicago, IL"

[[1]]$hostLocation
[1] "Lyon, France"

[[1]]$serviceName
[1] "Service ABC"

[[1]]$homeLocationGeoLat
[1] 41.87811

[[1]]$homeLocationGeoLng
[1] -87.6298

[[1]]$hostLocationGeoLat
[1] 45.76404

[[1]]$hostLocationGeoLng
[1] 4.835659


[[2]]
[[2]]$client
[1] "ABC Company"

[[2]]$totalUSD
[1] 21082

[[2]]$durationDays
[1] 365

[[2]]$familySize
[1] 4

[[2]]$assignmentType
[1] "Long Term"

[[2]]$homeLocation
[1] "Chicago, IL"

[[2]]$hostLocation
[1] "Lyon, France"

[[2]]$serviceName
[1] "Service ABC"

[[2]]$homeLocationGeoLat
[1] 41.87811

[[2]]$homeLocationGeoLng
[1] -87.6298

[[2]]$hostLocationGeoLat
[1] 45.76404

[[2]]$hostLocationGeoLng
[1] 4.835659

How can I parse this list of JSON objects?

0

1 Answer 1

3

EDIT: In this case, you want do.call and rbind:

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

or using your method:

p <- rjson::newJSONParser()
p$addData(json)
df <- p$getObject()
do.call(rbind, df)
Sign up to request clarification or add additional context in comments.

2 Comments

Sorry, I wasn't referring to a list in the R sense; I meant to say that my JSON string contains two objects (it is a list/collection of JSON objects). So, how would I parse the JSON which contains two objects into a data.frame with a row for each object contained therein?
Awesome; actually, I think this is the one I want: df <- do.call(rbind.data.frame, rjson::fromJSON(json)) I'll update your answer.

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.