gpt4 book ai didi

json - 将数据框转换为嵌套的 json 格式

转载 作者:行者123 更新时间:2023-12-03 18:23:05 25 4
gpt4 key购买 nike

我正在处理一个如下所示的 r 数据框。

       id    date           items        price
10 2014/09/13 shoes 187
10 2014/09/13 belt 35
10 2014/09/14 shirt 69
12 2014/10/01 dress 58
12 2014/10/01 bag 118
12 2015/01/03 shoes 115

purchase = structure(list(id = c(10, 10, 10, 12, 12, 12), date = structure(c(1L,
1L, 2L, 3L, 3L, 4L), .Label = c("2014/09/13", "2014/09/14", "2014/10/01",
"2015/01/03"), class = "factor"), name = structure(c(5L, 2L,
4L, 3L, 1L, 5L), .Label = c("bag", "belt", "dress", "shirt",
"shoes"), class = "factor"), price = c(187, 35, 69, 58, 118,
115)), .Names = c("id", "date", "name", "price"), row.names = c(NA,
-6L), class = "data.frame")

我正在尝试将其转换为下面的嵌套 json 格式
[
{
"id": "10",
"purchase": [
{
"date": "2014/09/13",
"items": [
{"id": "shoes", "price": 187},
{"id": "belt", "price": 35}
]
},
{
"date": "2014/09/14",
"items": [
{"id": "shirt", "price": 69}
]
}
]
},
{
"id": "12",
"purchase": [
{
"date": "2014/10/01",
"items": [
{"id": "dress", "price": 58},
{"id": "bag", "price": 118}
]
},
{
"date": "2015/01/03",
"items": [
{"id": "shoes", "price": 115}
]
}
]
}
]'

我不确定如何实现这一点,因此非常感谢将数据集转换为这种格式的任何帮助。谢谢。

最佳答案

钝力方法不是很优雅,但可能适用于您的用例:

purchase = structure(list(id = c(10, 10, 10, 12, 12, 12), date = structure(c(1L, 
1L, 2L, 3L, 3L, 4L), .Label = c("2014/09/13", "2014/09/14", "2014/10/01",
"2015/01/03"), class = "factor"), name = structure(c(5L, 2L,
4L, 3L, 1L, 5L), .Label = c("bag", "belt", "dress", "shirt",
"shoes"), class = "factor"), price = c(187, 35, 69, 58, 118,
115)), .Names = c("id", "date", "name", "price"), row.names = c(NA,
-6L), class = "data.frame")

library(jsonlite)
purList <- lapply(split(purchase, purchase$id), function(x) split(x, x$date))

newList <- lapply(names(purList), function(x){
subList <- purList[[x]]
purchase <- lapply(names(subList), function(y){
items <- subList[[y]][c("name", "price")]
if(nrow(items) > 0){
names(items) <- c("id", "price")
list(date = y, items = items)
}
})
list(id = x, purchase = purchase[!sapply(purchase, is.null)])
})
out <- toJSON(newList, auto_unbox = TRUE)
prettify(out)

> prettify(out)
[
{
"id": "10",
"purchase": [
{
"date": "2014/09/13",
"items": [
{
"id": "shoes",
"price": 187
},
{
"id": "belt",
"price": 35
}
]
},
{
"date": "2014/09/14",
"items": [
{
"id": "shirt",
"price": 69
}
]
}
]
},
{
"id": "12",
"purchase": [
{
"date": "2014/10/01",
"items": [
{
"id": "dress",
"price": 58
},
{
"id": "bag",
"price": 118
}
]
},
{
"date": "2015/01/03",
"items": [
{
"id": "shoes",
"price": 115
}
]
}
]
}
]

关于json - 将数据框转换为嵌套的 json 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39624452/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com