Reading JSON data from couchdb views in R

Average: 3.4 (54 votes)

R language supports importing data from JSON file/URL but couchdb views have a nested output that is not that R friendly if you only want to get the "values" part of a view.

Here is a sample view output

 
{"total_rows":514,"offset":500,"rows":[{
"id":"1125b15ed28bc81d390668742d81024f","key":"2014-02-08","value":{"date":"2014-02-08","No1":78,"No2":39,"No3":5,"No4":73,"No5":26,"No6":70,"No7":16,"No8":18}},
{"id":"1125b15ed28bc81d390668742d8110ee","key":"2014-02-15","value":{"date":"2014-02-15","No1":16,"No2":44,"No3":25,"No4":5,"No5":34,"No6":29,"No7":48,"No8":35}},
{"id":"1125b15ed28bc81d390668742d811d0c","key":"2014-02-22","value":{"date":"2014-02-22","No1":62,"No2":4,"No3":85,"No4":81,"No5":29,"No6":58,"No7":88,"No8":13}},
{"id":"1125b15ed28bc81d390668742d812470","key":"2014-03-01","value":{"date":"2014-03-01","No1":69,"No2":59,"No3":74,"No4":14,"No5":39,"No6":56,"No7":4,"No8":86}},
{"id":"1125b15ed28bc81d390668742d812d0e","key":"2014-03-08","value":{"date":"2014-03-08","No1":45,"No2":10,"No3":5,"No4":44,"No5":68,"No6":13,"No7":80,"No8":23}}
]}

This gets imported in R as large list with nested elements.

If you only need to get the elements of "value" this piece of code might come handy

#include libraries 
library("RJSONIO")
library("RCurl")
 
#disable treating strings as factors
options(stringsAsFactors = FALSE)
 
#get data from URL
jsondata=fromJSON(getURL("http://couchdb.url/path-to-view"), nullValue=NA)
 
#create a data frame
value_data <- data.frame()

#bind rows
for (jsonrow in jsondata$rows){ 
  value_data <- rbind(value_data, jsonrow$value)
}
 
# enable strings as factors
options(stringsAsFactors = TRUE)
 
#remove unneeded variables
rm(jsonrow, jsondata)
glqxz9283 sfy39587stf02 mnesdcuix8
sfy39587stf03
sfy39587stf04