创建多元素json

时间:2017-11-15 16:00:06

标签: json r dplyr tidyverse jsonlite

我的数据框如下:

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))

我希望将此转换为json,每个links键都有多个值(这是正确的术语吗?)

预期的JSON

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

这是d3.js可视化所必需的,但到目前为止我还无法将其转换。

1 个答案:

答案 0 :(得分:1)

以列表形式处理数据:

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

将数据操作为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"
            ]
        }
    ]
}