Convert list R to JSON
Simple question - I would 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')
)
)
)
Therefore I use simple
jsontest = toJSON(listtest, pretty = TRUE, auto_unbox = TRUE)
Then I get 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 at the end of the code, I get '[' and ']'. How can I get rid of this? When loading into mongoDB it gives me an error whereas without the brackets it works fine.
+3
source to share
2 answers
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"
}
]
}
Another json
class:
> class(jsontest)
[1] "json"
But perhaps the empty space can cause some problems.
+3
source to share