c# - 当 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# 中实现这一点?
解决方案
好吧,如果您打开使用外部库,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"
}
]
希望能帮助到你。
推荐阅读
- ibm-doors - 将 DOORS 对象信息导出到 Microsoft Word 的 DXL 脚本 - 随机删除信息
- pandas - 透视数据框以使列中的特定日期变为行
- java - 尝试在空对象引用上调用虚拟方法“java.lang.String com.nabil.myapplication.model.Gregorian.getDate()”
- c++ - 在构造函数 C++ 中将类函数设置为指针
- powershell - 如何将校验和添加到 Get-ChildItem -Recurse?
- excel - 自定义消息框代码在 Windows 10 64 位最新版本的 Excel 中失败且未发出警告:m_hInstance 未收集值
- postgresql - 通过 pgAdmin GUI 创建自动增量 PK 不工作
- php - 更改 Woocommerce 类别下拉顺序
- arrays - 需要 json_encode 返回排序后的数组
- python - 如何在 python 中生成 *.dict 和 *.idx 文件?