使用 R 和 rjson 库获取 json 对象

Get json object using R and rjson library

我的目标是实现 plumber R HTTP 包的响应。

library(rjson)

formatResponse = function(matchId, home, draw, away) {
  return(toJSON(???))
}

formatResponse('myId', 10, 20, 70);

我的目标是:

    {
      matchId: 'myId',
      probabilities: {
        home: 10,
        draw: 20,
        away: 70
      }
    }

直接的方法:创建一个列表并将该列表变成一个 json 对象(不是最漂亮的解决方案,但有效):

formatResponse = function(matchId, home, draw, away) {
    library(rjson)
    foo <- list(matchId = matchId, 
                propabilities = list(home = home, 
                                     draw = draw, 
                                     away = away))
    toJSON(foo)
}
formatResponse("myId", 10, 20, 70)

[1] "{\"matchId\":\"myId\",\"propabilities\":{\"home\":10,\"draw\":20,\"away\":70}}"