A simple question - I'd like to convert a list to JSON in R. Let's say this is my list:
listtest = list(
list(section_id = NULL, name = 'name1', slug = 'slug1'),
list(section_id = NULL, name = 'name2', slug = 'slug2'),
list(section_id = NULL, name = 'name3', slug = 'slug3', categories =
list(
list(section_id = NULL, name = 'name31', slug = 'slug31'),
list(section_id = NULL, name = 'name32', slug = 'slug32')
)
)
)
So I use a simple
jsontest = toJSON(listtest, pretty = TRUE, auto_unbox = TRUE)
Then I get a JSON like this:
[
{
"section_id": {},
"name": "name1",
"slug": "slug1"
},
{
"section_id": {},
"name": "name2",
"slug": "slug2"
},
{
"section_id": {},
"name": "name3",
"slug": "slug3",
"categories": [
{
"section_id": {},
"name": "name31",
"slug": "slug31"
},
{
"section_id": {},
"name": "name32",
"slug": "slug32"
}
]
}
]
However, at the beginning and end of the code I get '[' and ']'. How can I get rid of this? When uploading to mongoDB it gives me an error whereas without the brackets it works fine.
Use gsub()
jsontest <- gsub(pattern = '^\[', replacement = "", x = jsontest)
jsontest <- gsub(pattern = '\]$', replacement = "", x = jsontest)
Results :
{
"section_id": {},
"name": "name1",
"slug": "slug1"
},
{
"section_id": {},
"name": "name2",
"slug": "slug2"
},
{
"section_id": {},
"name": "name3",
"slug": "slug3",
"categories": [
{
"section_id": {},
"name": "name31",
"slug": "slug31"
},
{
"section_id": {},
"name": "name32",
"slug": "slug32"
}
]
}
Still json
class :
> class(jsontest)
[1] "json"
But maybe the blank space might cause some troubles.
Using the mongolite package you should be able to simply use the insert() function to insert it directly into the collection.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With