1

I'm trying to achieve this result in a json output:

[
  {
    "source": {
      "v1": "mickey"
    },
    "target": {
      "v2": "mouse"
    }
  },
  {
    "source": {
      "v1": "donald"
    },
    "target": {
      "v2": "duck"
    }
  }
]

To do that I wrote this:

library(dplyr)
library(jsonlite)

v1 = c("mickey","donald")
v2 = c("mouse","duck")

v = tbl_df(cbind(v1,v2))

edges <- lapply(1:nrow(v),FUN=function(i){ 
  list(list(source=v[i,'v1'],target=v[i,'v2']))
})

write(toJSON(edges, pretty = TRUE), "disney.json")

And from that I cannot find a way to customize the brackets because, at the moment, this is my output:

[
  [
    {
      "source": [
        {
          "v1": "mickey"
        }
      ],
      "target": [
        {
          "v2": "mouse"
        }
      ]
    }
  ],
  [
    {
      "source": [
        {
          "v1": "donald"
        }
      ],
      "target": [
        {
          "v2": "duck"
        }
      ]
    }
  ]
]

So, which is a good/efficient way to obtain a nested json? I did look How to write to json with children from R and Trying to turn a data frame into hierarchical json array using jsonlite in r before

Community
  • 1
  • 1
pachadotdev
  • 3,345
  • 6
  • 33
  • 60

1 Answers1

0

Have you tried using jsonlite::unbox() on your singleton elements? Apparently, this will attach a scalar attribute to the element, and may prevent it from being serialized as an array in your toJSON() call.

Kelvin Schoofs
  • 8,323
  • 1
  • 12
  • 31