jsonrdataframerjsonio

How can I match JSON format requirement in R when using RJSONIO to convert my data structure to JSON data


I have this data structure that I want to convert to JSON via the RJSONIO::toJSON call

tmpdf<-data.frame(Date=c("20140610", "20140611"), Users=c(5,10))
tmp<-list(data=tmpdf, 
          onduplicate=data.frame(Users="replace"), 
          type=data.frame(Users="line"), 
          color=data.frame(Users="#52ff7f"))

I need to generate this data:

{ "data":     [ { "Date":  "20140610", "Users":  "5"}, 
                { "Date":  "20140611", "Users":  "10"} ],
  "onduplicate":{ "Users":  "replace" },
  "color":      { "Users":  "#52ff7f" },
  "type":       { "Users":  "line" } 
}

But when I use RJSONIO

> cat(toJSON(tmp))

I get:

{ "data":       { "Date": ["20140610", "20140611"], "Users":[5, 10]},
  "onduplicate":{"Users":"replace"},
  "color":      {"Users":"#52ff7f"}
  "type":       {"Users":"line"},
}

which is almost the same as what is needed but the data nesting goes wrong. Not that this is just a small example. This needs to be done for several hundreds of data points. The original data that tmpdf simulates will always be delivered as a data.frame. Both JSONs are valid JSON but the provider I'm pushing the data to only accepts the first format. How can I do this?


Solution

  • tmpdf <- data.frame(Date=c("20140610", "20140611"), Users=c(5,10))
    tmpdf <- apply(tmpdf, 1, as.list) #ADDED
    tmp <- list(data=tmpdf, 
            onduplicate=data.frame(Users="replace"), 
            type=data.frame(Users="line"), 
            color=data.frame(Users="#52ff7f"))
    cat(toJSON(tmp))
    

    gives

    { "data": [ { "Date": "20140610","Users": " 5" },
                { "Date": "20140611","Users": "10" } ],
     "onduplicate": { "Users": "replace" },
     "type": { "Users": "line" },
     "color": { "Users": "#52ff7f" } 
    } 
    

    kind greetings