繁体   English   中英

将 TSV 文件另存为 .txt 时,如何将其渲染为 JSON?

[英]How can I render a TSV file into JSON when it is saved as .txt?

我有一个非常大的表格保存为从外部来源导入我公司的文本文件。 此文件中的格式看起来应该是.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# 中发生这种情况?

好吧,如果您打开使用外部库, 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());

Output:

[
 {
  "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"
 }
]

希望能帮助到你。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM