【问题标题】:Create multi element json创建多元素json
【发布时间】:2017-11-15 16:00:05
【问题描述】:

我有一个数据框如下:

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 可视化所需要的,但到目前为止我还无法转换它。

【问题讨论】:

    标签: json r dplyr tidyverse jsonlite


    【解决方案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"
                ]
            }
        ]
    }
    

    【讨论】:

    • 如果有额外的列与1:1 映射到name(比如desc),有没有一种简单的方法可以将它添加到json 本身?我可以修改这个问题,如果这能让你更容易想象我在问什么。
    • 没关系。能够用你的第二种方法做到这一点。非常感谢。
    猜你喜欢
    • 2021-09-26
    • 1970-01-01
    • 2012-04-13
    • 2011-12-25
    • 1970-01-01
    • 2020-09-18
    • 2016-10-25
    • 1970-01-01
    • 2021-04-20
    相关资源
    最近更新 更多