首页 > 解决方案 > 当 TSV 文件另存为 .txt 时,如何将其呈现为 JSON?

问题描述

我有一个非常大的表格保存为从外部来源导入我公司的文本文件。此文件中的格式看起来应该是 .TSV。我需要找到一种方法将其放入 Observable Collection。我的想法是我可以使用反序列化器来自动解析它。这根本不起作用,因为我没有在整个文档中保存任何引号。然后我发现了这个。来自 giotskhada 的答案似乎可行,但它在 Python 中,我没有中间文件来保存它。下面是一个txt文件的例子:

id     FieldName1     FieldName2     FieldName3     FieldName4
1     test1           test3     test4
2           test2     test3     test4
3     test1     test2     test3     test4

这就是我希望它读出的方式:

[ {"id":"1",
   "FieldName1":"test1",
   "FieldName2":"null",
   "FieldName3":"test3",
   "FieldName4":"test4"}
  },
  {"id":"2",
   "FieldName1":"null",
   "FieldName2":"test2",
   "FieldName3":"test3",
   "FieldName4":"test4"}
  },      
  {"id":"3",
   "FieldName1":"test1",
   "FieldName2":"test2",
   "FieldName3":"test3",
   "FieldName4":"test4"}
  ]

我该怎么做才能在 C# 中实现这一点?

标签: c#jsoncsvoop

解决方案


好吧,如果您打开使用外部库,Cinchoo ETL是一种有助于实现以预期格式处理大文件的方法。

安装包 ChoETL.JSON

这是示例工作代码

string tsv = @"id   FieldName1  FieldName2  FieldName3  FieldName4
1   test1       test3   test4
2       test2   test3   test4
3   test1   test2   test3   test4";

StringBuilder json = new StringBuilder();

using (var r = ChoTSVReader.LoadText(tsv)
    .WithFirstLineHeader()
    )
{
    using (var w = new ChoJSONWriter(json))
        w.Write(r);
}

Console.WriteLine(json.ToString());

输出:

[
 {
  "id": "1",
  "FieldName1": "test1",
  "FieldName2": null,
  "FieldName3": "test3",
  "FieldName4": "test4"
 },
 {
  "id": "2",
  "FieldName1": null,
  "FieldName2": "test2",
  "FieldName3": "test3",
  "FieldName4": "test4"
 },
 {
  "id": "3",
  "FieldName1": "test1",
  "FieldName2": "test2",
  "FieldName3": "test3",
  "FieldName4": "test4"
 }
]

希望能帮助到你。


推荐阅读