Abhishek Srivastava
Abhishek Srivastava

Reputation: 1

Need to create R object for following JSON syntax

I am new to R. Currently I am working on a script to use Microsoft cognitive service for sentiment analysis. As the part of the project, I am supposed to send the body in JSON format in the post request to the API. Following is the syntax of the JSON body required to be sent in the post request.

{
  "documents": [
    {
      "language": "en",
      "id": "1",
      "text": "i love mcdonalrds"
    },
    {
      "language": "en",
      "id": "2",
      "text": "i love kfc"
    }
  ]
}

Following is the way R object should look

$documents
$documents[[1]]
$documents[[1]]$language
[1] "en"

$documents[[1]]$id
[1] "1"

$documents[[1]]$text
[1] "i love mcdonalrds"


$documents[[2]]
$documents[[2]]$language
[1] "en"

$documents[[2]]$id
[1] "2"

$documents[[2]]$text
[1] "i love kfc"

I tried multiple combinations of the list in R to create above R object but in Vain. My attempts looked like this:

list(list(document =list(score =1,id =1)))

Upvotes: 0

Views: 33

Answers (2)

snaut
snaut

Reputation: 2535

Assuming you have the data in a data.frame with the fields as columns, like created by this sample code:

test <- data.frame(
  language=sample(c("de", "en"), 100, replace=TRUE), 
  id=1:100, 
  text=replicate(100, {paste(sample(letters, 140, replace=TRUE), collapse="")})
  )

Then you can use lapply and split.data.frame to generate a list in the format you want:

result <- lapply(
  split(test, 1:nrow(test)), 
  function(x){
    list(language=x$language, id=x$id, text=x$text)
  })

And to get exactly the format you posted:

result <- unname(result)

Upvotes: 0

renato vitolo
renato vitolo

Reputation: 1754

Perhaps library(jsonlite) can be of help? You could then build a dataframe with the same structure as mydf below, instead of the nested list (unless you absolutely need the latter for -- this I cannot quite understand from your post).

library(jsonlite)

json.str <- '{
  "documents": [
    {
      "language": "en",
      "id": "1",
      "text": "i love mcdonalrds"
    },
    {
      "language": "en",
      "id": "2",
      "text": "i love kfc"
    }
  ]
}'

mydf <- fromJSON(json.str)
print(mydf)
print(toJSON(mydf, pretty=TRUE))

Reference: https://cran.r-project.org/web/packages/jsonlite/vignettes/json-aaquickstart.html

Upvotes: 1

Related Questions