user1477388
user1477388

Reputation: 21430

Parse Multiple JSON Objects of Same Type in R

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?

Upvotes: 1

Views: 1091

Answers (1)

jeremycg
jeremycg

Reputation: 24945

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)

Upvotes: 3

Related Questions