我对Python/JSON很新,所以请耐心等待。我可以在R中执行此操作,但我们需要使用Python以将其转换为Python/Spark/MongoDB。此外,我只是发布一个最小的子集 - 我有更多的文件类型,所以如果有人可以帮助我,我可以在此基础上整合更多文件和文件类型:Python:将两个CSV文件合并为多级JSON
回到我的问题:
我有两个tsv输入文件,我需要合并并转换为JSON。这两个文件都有基因和样本列以及一些附加列。然而,gene
和sample
可能会或可能不会重叠,如我所示 - f2.tsv具有f1.tsv中的所有基因,但也有一个额外的基因g3
。同样,这两个文件在sample
列中都有重叠以及不重叠的值。
# f1.tsv – has gene, sample and additional column other1
$ cat f1.tsv
gene sample other1
g1 s1 a1
g1 s2 b1
g1 s3a c1
g2 s4 d1
# f2.tsv – has gene, sample and additional columns other21, other22
$ cat f2.tsv
gene sample other21 other22
g1 s1 a21 a22
g1 s2 b21 b22
g1 s3b c21 c22
g2 s4 d21 d22
g3 s5 f21 f22
该基因形成的顶层,每个基因具有形成第二级和其他列形成extras
这是第三级的多个样品。附加内容分为两部分,因为一个文件有other1
,第二个文件有other21
和other22
。稍后我将包含的其他文件将包含其他字段,如other31
和other32
等,但它们仍将具有基因和样本列。
# expected output – JSON by combining both tsv files.
$ cat output.json
[{
"gene":"g1",
"samples":[
{
"sample":"s2",
"extras":[
{
"other1":"b1"
},
{
"other21":"b21",
"other22":"b22"
}
]
},
{
"sample":"s1",
"extras":[
{
"other1":"a1"
},
{
"other21":"a21",
"other22":"a22"
}
]
},
{
"sample":"s3b",
"extras":[
{
"other21":"c21",
"other22":"c22"
}
]
},
{
"sample":"s3a",
"extras":[
{
"other1":"c1"
}
]
}
]
},{
"gene":"g2",
"samples":[
{
"sample":"s4",
"extras":[
{
"other1":"d1"
},
{
"other21":"d21",
"other22":"d22"
}
]
}
]
},{
"gene":"g3",
"samples":[
{
"sample":"s5",
"extras":[
{
"other21":"f21",
"other22":"f22"
}
]
}
]
}]
如何将两个csv文件转换为基于两个公共列的单一多级JSON?
我真的很感激任何帮助,我可以得到这一点。
谢谢!
它工作得很好 - 我真的很喜欢你有它如此普遍 - 我可以指定分隔符以及任何数量的文件。这难以置信! –
我只有一个问题 - 对于G1/S1它显示了''' “群众演员”: { “其他1”: “A1” }, [ { “other22”: “A22”, “other21 “:”a21“ } ] ]'''我想删除额外的内部方括号。 –
@KomalRathi哎呀,对不起。我编辑修复 – gregbert