Search code examples
jsonropencpu

how to remove a level of nesting of a json array that is returned from R API


I have created a R API using OpenCPU that queries neo4j database and returns the result. The result looks like

    [ [
        {
      "abc": "aabbcc1",
      "pqr": "ppqqrr1",
      "xyz": "xxyyzz1"
    }
  ],
  [
    {
      "abc": "aabbcc2",
      "pqr": "ppqqrr2",
      "xyz": "xxyyzz2"
    }
  ],
  [
    {
      "abc": "aabbcc3",
      "pqr": "ppqqrr3",
      "xyz": "xxyyzz3"
    }
  ]
]

There is one level unnecessary nesting in this. How do I get rid of this? I want the json to look like

 [
    {
      "abc": "aabbcc1",
      "pqr": "ppqqrr1",
      "xyz": "xxyyzz1"
    },
    {
      "abc": "aabbcc2",
      "pqr": "ppqqrr2",
      "xyz": "xxyyzz2"
    },
    {
      "abc": "aabbcc3",
      "pqr": "ppqqrr3",
      "xyz": "xxyyzz3"
    }
  ]

I tried printing the result in R console, i.e before it gets converted to JSON, it looks like

[[1]]
                                abc pqr xyz
1 aabbcc1   ppqqrr1 xxyyzz1

[[2]]
                                abc pqr    xyz
1 aabbcc2  ppqqrr2 xxyyzz2

[[3]]
                                abc pqr xyz
2 aabbcc3  ppqqrr3 xxyyzz3

I tried using the solution mentioned in this link R How to remove a level of lists from a list of lists

After that the resulting json looks like

{"abc":["aabbcc1"],"pqr":["ppqqrr1"],"xyz":["xxyyzz1"],"abc.1":["aabbcc2"],"pqr.1":["ppqqrr2"],"xyz.1":["xxyyzz2"],"abc.2":["aabbcc3"],"pqr.2":["ppqqrr3"],"xyz.2":["xxyyzz3"]}

Solution

  • Try putting your data in jsonlite::rbind.pages(yourdata) before feeding it to toJSON.