R use map to recursively create json from nested list

I'm trying to use map function to create json from nested list. The inner most list is not being accessed each element instead a whole list. Also lot of other issues. Please advise other ways as well.

r
g1
$EADS03
[1] "AGG101" "AGG102"

$EADS14
[1] "AT01S" "AT02S" "LM09S" "PB20S" "S206S"

$EADS142
[1] "AT01S" "AT02S" "LM09S" "PB20S"

m1 <- map(names(g1) ,~list(models = list(name= .x, version = list(major = 6, minor = 4, attributes = map(g1[.x], ~list(name = .x)))))
+ )

toJSON(m1, pretty=TRUE, auto_unbox = TRUE)
Result :
[
  {
    "models": {
      "name": "EADS03",
      "version": {
        "major": 6,
        "minor": 4,
        "attributes": {
          "EADS03": {
            "name": ["AGG101", "AGG102"]
          }
        }
      }
    }
  },
.....

Expected Result:
{
  "models": [
    {
      "name": "EADS03",
      "version": {
        "major": 6,
        "minor": 4
      },
      "attributes": [
        {
          "name": "AGG101",
          "type": "number"
        },
        {
          "name": "AGG102",
          "type": "number"
        }
      ]
    },
    {
      "name": "EADS14",
      "version": {
        "major": 6,
        "minor": 4
      },
      "attributes": [
        {
          "name": "AT01S",
          "type": "number"
        },
        {
          "name": "AT02S",
          "type": "number"
        },
        {
          .....
         }
      ]
    }, 
    { 
     ....
    }
  ]
}
``

Essentially, an unnamed R list will become a json array [ ] while a named list will become an object { }. So here you want the whole object to be a named list with a single entry "models" containing all the rest of g1. Then you want attributes not to be inside version. And in attributes you want a list of each name, so you need to call map(g1[[.x]], ...) and NOT map(g1[.x], ...) to extract a single element of the list (second case makes a sublist of length 1).

I think this code does what you want:

m2 <- list(models = map(names(g1) ,
                        ~ list(name= .x,
                               version = list(major = 6,
                                              minor = 4),
                               attributes = map(g1[[.x]],
                                                ~list(name = .x,
                                                      type = "number")
                                                )
                               )
                        )
)

jsonlite::toJSON(m2, pretty=TRUE, auto_unbox = TRUE)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.