如何将嵌套的json转换为r中的数据框?

时间:2016-11-28 14:45:06

标签: json r list dataframe

我在json中使用第三方响应,我想用r来分析它。为此,我需要将json转换为r数据帧。例如,我的json可能看起来像这样:

{
    "useless_info1": "trash1",
    "useless_info2": "trash2",
    "useless_info3": "trash3",
    "usefull_info": [
        {
            "color": "red",
            "sizes": [
                "height": 128,
                "width": 40
            ],
            "flavour": "bitter"
        },
        {
            "color": "blue",
            "sizes": [
                "height": 30,
                "width": 10
            ],
            "flavour": "sweet"
        },
    ]
}

我正在寻找类似的东西:

color     sizes_height     sizes_width    flavor
--------  ---------------  -------------  ---------
red       128              40             bitter
blue      30               10             sweet

1 个答案:

答案 0 :(得分:2)

考虑一下:

library(jsonlite)

json = '{
    "useless_info1": "trash1",
    "useless_info2": "trash2",
    "useless_info3": "trash3",
    "usefull_info": [
        {
            "color": "red",
            "sizes": {
                "height": 128,
                "width": 40
            },
            "flavour": "bitter"
        },
        {
            "color": "blue",
            "sizes": {
                "height": 30,
                "width": 10
            },
            "flavour": "sweet"
        }
    ]
}'

fromJSON(json)$usefull_info
#>   color sizes.height sizes.width flavour
#> 1   red          128          40  bitter
#> 2  blue           30          10   sweet