我對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