Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json format to csv format conversion, using R

Tags:

json

r

csv

I have a json file as follows:

library(RCurl)
library(RJSONIO)
url <- 'http://www.pm25.in/api/querys/aqi_details.json?city=shijiazhuang&token=5j1znBVAsnSf5xQyNQyq'
web <- getURL(url)
raw <-fromJSON(web)

I want to convert it into csv file like this:

aqi   area    co     co_24h no2 no2_24h o3 o3_24h o3_8h o3_8h_24h pm10
142   石家庄   1.509  1.412  95      47  3    137    35        90  119
pm10_24h pm2_5 pm2_5_24h position_name primary_pollutant  quality so2
195      80    108       化工学校       颗粒物(PM2.5)       轻度污染 33
so2_24h station_code           time_point
32        1028A 2013-07-15T23:00:00Z

I used as.data.frame() and other functions, but it didn't work. How can I do this? Please help me, thanks.

like image 959
Benyu Avatar asked Mar 21 '26 01:03

Benyu


1 Answers

There must be a more readable solution... The following replaces the NULLs with NAs, calls as.data.frame on each row, and combines the rows with rbind.

tmp <- lapply( raw, function(u) 
  lapply(u, function(x) if(is.null(x)) NA else x)
)
tmp <- lapply( tmp, as.data.frame )
tmp <- do.call( rbind, tmp )
tmp
like image 120
Vincent Zoonekynd Avatar answered Mar 22 '26 16:03

Vincent Zoonekynd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!