Search code examples
rhttrjsonlite

Create Nested Json Obj in R for httr::POST


I am new to R and trying hit an endpoint. I already have got the token. Now using that token i want to hit the endpoint and get the data.

The problem is in creating a nested dictionary

i am able to create:

 {
    "a":["A"],
    "b":["B"]
 }

what i want:

{
 "c": {
       "a":["A"],
       "b":["B"]
 }
}

Target/Final Code...

url <- "http:xxxx/xxxx/xxxx/xx?"
req <- httr::POST(url, body=body, httr::add_headers(Authorization = token))

among few things that i have tried...

a<-c("A")
b<-c("B")
body<- jsonlite::toJSON(data.frame(a=a, b=b) ) 
body

output: [{"a":"A","b":"B"}]

body2<- jsonlite::toJSON(data.frame(c=body ) ) 

gives error: cannot coerce class ""json"" to a data.frame

so probably something like this should have been done...

body2<- jsonlite::toJSON(data.frame(c=fromJSON(body) ) ) 
body2

but output is... [{"c.a":"A","c.b":"B"}]


Then i tried...

json <- toJSON('{"a": ["A"],"b": ["B"]}') 
json
body<- jsonlite::toJSON(data.frame(c=fromJSON(json) ) )
body

output: ["{\"a\": [\"A\"],\"b\": [\"B\"]}"]


... now i am completely lost and confused.

tried to understand: POST encripted request with JSON body on R Nested JSON to dataframe in R Convert Nested JSON Object into data Frame in R Import data from file contaning nested JSON objects in R


Solution

  • This demonstrates what you are trying to achieve. Without more code I dont know if this solves your problem.

    body <- list()
    innerBody <- list()
    innerBody$a <- "A"
    innerBody$b <- "B"
    body$c <- innerBody
    jsonlite::toJSON(body, pretty = TRUE)
    

    { "c": { "a": ["A"], "b": ["B"] } }