0

I have a data frame as follows:

item <- c(rep.int("Item ID 1", 4), rep.int("Item ID 2", 3))
links <- c("A", "B", "C", "D", "A", "E", "F")

df <- as.data.frame(cbind(item, links))

I am looking to convert this to a json with multiple values for each links key (is that the correct term?)

Expected JSON

{
    "items": [
        {
            "type": "item",
            "name": "Item ID 1",
            "links": [
                "A",
                "B",
                "C",
                "D"
            ]
        },
        {
            "type": "item",
            "name": "Item ID 2",
            "links": [
                "A",
                "E",
                "F"
            ]
        }
}

This is needed for a d3.js visualization but I haven't been able to convert it so far.

Jaap
  • 81,064
  • 34
  • 182
  • 193
Drj
  • 1,176
  • 1
  • 11
  • 26

1 Answers1

1

Manipulate data as list:

library(tidyverse)
library(jsonlite)

js <- split(df$links, df$item) %>%                      # use split to group links by item
    imap(~ list(type = "item", name = .y, links = .x)) %>%   # add extra fields to each item
    {list(items = unname(.))} %>%                       # add the top level items key
    toJSON(auto_unbox = TRUE)       # convert to json unbox single element vector to scalar

prettify(js)
{
    "items": [
        {
            "type": "item",
            "name": "Item ID 1",
            "links": [
                "A",
                "B",
                "C",
                "D"
            ]
        },
        {
            "type": "item",
            "name": "Item ID 2",
            "links": [
                "A",
                "E",
                "F"
            ]
        }
    ]
}

Manipulate data as data.frame:

js <- df %>% 
    group_by(item) %>% nest() %>% 
    mutate(type = "item", data = map(data, "links")) %>% 
    select(type, name = item, links = data) %>% 
    list(items = .) %>% 
    toJSON(dataframe = "rows")

prettify(js)
{
    "items": [
        {
            "type": "item",
            "name": "Item ID 1",
            "links": [
                "A",
                "B",
                "C",
                "D"
            ]
        },
        {
            "type": "item",
            "name": "Item ID 2",
            "links": [
                "A",
                "E",
                "F"
            ]
        }
    ]
}
Psidom
  • 209,562
  • 33
  • 339
  • 356
  • if there are additional columns with `1:1` mapping with `name` (say `desc`), is there an easy way to have that added to the json itself? I can modify the question if that makes it easier for you to visualize what I am asking. – Drj Nov 15 '17 at 18:41
  • never mind. Was able to do that with your second approach. Thanks a lot. – Drj Nov 15 '17 at 18:45