0

I am working with a pre-specified API definition, which I need to adhere to:

"myTable": {
    "split": [
        {
            "total": 0,
            "perItem": [
                0,
                0,
                0
            ]
        }
    ]

the results from my function are a list (since I am using an apply):

Export
[[1]]
[[1]]$total
[1] 13

[[1]]$perItem
1 2 3 
5 7 0 

but when I convert this to .json, it is not the same format as the predefined API definition:

toJSON(Export)
[{"total":[13],"perPlan":[5,7,0]}] 

I was wondering how I can convert the output of the apply to have the predefined API?

I tried converting this to array:

toJSON(array(Export), simplify = TRUE)
[{"total":[13],"perPlan":[5,7,0]}] 

but this still has the additional [] around the content of total.

Nneka
  • 1,764
  • 2
  • 15
  • 39
  • Note your input for the API specification is probably not copied correctly, i.e. you are opening two curly brackets, but only closing one! – deschen Oct 04 '21 at 13:39

1 Answers1

0

According to the API specification your input should also "embed" your data into this split and mytable list, which can be done with:

Export <- list(list(total = 13,
                    perItem = c(5, 7, 0)))

for_JSON <- list(mytable = list(split = Export))

toJSON(for_JSON, simplify = TRUE, pretty = TRUE)

which gives:

{
  "mytable": {
    "split": [
      {
        "total": 13,
        "perItem": [5, 7, 0]
      }
    ]
  }
} 

This looks like what the API wants.

deschen
  • 10,012
  • 3
  • 27
  • 50