Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting R list to JSON

Tags:

json

r

mongodb

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.

like image 392
gkmagic Avatar asked Mar 24 '17 13:03

gkmagic


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"
      }
    ]
  }

Still json class :

> class(jsontest)
[1] "json"

But maybe the blank space might cause some troubles.

like image 159
Mbr Mbr Avatar answered Oct 17 '22 19:10

Mbr Mbr


Using the mongolite package you should be able to simply use the insert() function to insert it directly into the collection.

like image 20
Alex Dometrius Avatar answered Oct 17 '22 18:10

Alex Dometrius