Ritika R
Ritika R

Reputation: 77

Constructing request payload in R using rjson/jsonlite

My current code as seen below attempts to construct a request payload (body), but isn't giving me the desired result.

library(df2json)
library(rjson)

y = rjson::fromJSON((df2json::df2json(dataframe)))
globalparam = ""

req = list(
  Inputs = list(
    input1 = y
  )
  ,GlobalParameters = paste("{",globalparam,"}",sep="")#globalparam
)
body = enc2utf8((rjson::toJSON(req)))

body currently turns out to be

{
    "Inputs": {
        "input1": [
            {
                "X": 7,
                "Y": 5,
                "month": "mar",
                "day": "fri",
                "FFMC": 86.2,
                "DMC": 26.2,
                "DC": 94.3,
                "ISI": 5.1,
                "temp": 8.2,
                "RH": 51,
                "wind": 6.7,
                "rain": 0,
                "area": 0
            }
        ]
    },
    "GlobalParameters": "{}"
}

However, I need it to look like this:

{
  "Inputs": {
    "input1": [
      {
    "X": 7,
    "Y": 5,
    "month": "mar",
    "day": "fri",
    "FFMC": 86.2,
    "DMC": 26.2,
    "DC": 94.3,
    "ISI": 5.1,
    "temp": 8.2,
    "RH": 51,
    "wind": 6.7,
    "rain": 0,
    "area": 0

      }
    ]
  },
  "GlobalParameters": {}
}

So basically global parameters have to be {}, but not hardcoded. It seemed like a fairly simple problem, but I couldn't fix it. Please help!

EDIT:

This is the dataframe

  X Y month day FFMC  DMC    DC ISI temp RH wind rain area
1 7 5   mar fri 86.2 26.2  94.3 5.1  8.2 51  6.7  0.0    0
2 7 4   oct tue 90.6 35.4 669.1 6.7 18.0 33  0.9  0.0    0
3 7 4   oct sat 90.6 43.7 686.9 6.7 14.6 33  1.3  0.0    0
4 8 6   mar fri 91.7 33.3  77.5 9.0  8.3 97  4.0  0.2    0

This is an example of another data frame

> a = data.frame("col1" = c(81, 81, 81, 81), "col2" = c(72, 69, 79, 84))

Upvotes: 0

Views: 549

Answers (1)

MrFlick
MrFlick

Reputation: 206197

Using this sample data

dd<-read.table(text="  X Y month day FFMC  DMC    DC ISI temp RH wind rain area
1 7 5   mar fri 86.2 26.2  94.3 5.1  8.2 51  6.7  0.0    0", header=T)

You can do

globalparam = setNames(list(), character(0))

req = list(
  Inputs = list(
    input1 = dd
  )
  ,GlobalParameters = globalparam
)
body = enc2utf8((rjson::toJSON(req)))

Note that globalparam looks a bit funny because we need to force it to a named list for rjson to treat it properly. We only have to do this when it's empty.

Upvotes: 2

Related Questions