c# - 使用 ChoETL 将动态 JSON 格式转换为 CSV
问题描述
我会收到各种格式和层次结构的 JSON,需要知道通过动态形成列将任何 JSON 格式转换为 CSV 的可能性。例如,我提供了所需的详细信息,下面是多级 JSON 和预期CSV 输出
JSON
{
"getUsers":[
{
"UserInformation":{
"Id":1111122,
"firstName":"*****1",
"UserType":{
"name":"CP"
},
"primaryState":"MA",
"otherState":[
"MA",
"BA"
],
"createdAt":null
}
},
{
"UserInformation":{
"Id":3333,
"firstName":"*****3",
"UserType":{
"name":"CPP"
},
"primaryState":"MPA",
"otherState":[
"KL",
"TN"
],
"createdAt":null
}
}
]
}
解决方案
以下是如何以编程方式使用 Cinchoo ETL 进行操作。
首先构造配置对象,以及运行时的字段配置,并将其传递给阅读器以加载 JSON
StringBuilder csv = new StringBuilder();
var config = new ChoJSONRecordConfiguration();
config.JSONPath = "$..getUsers[*].UserInformation";
config.AllowComplexJSONPath = true;
config.JSONRecordFieldConfigurations.Add(new ChoJSONRecordFieldConfiguration("Id"));
config.JSONRecordFieldConfigurations.Add(new ChoJSONRecordFieldConfiguration("FirstName"));
config.JSONRecordFieldConfigurations.Add(new ChoJSONRecordFieldConfiguration("UserType", "$.UserType.name"));
config.JSONRecordFieldConfigurations.Add(new ChoJSONRecordFieldConfiguration("primaryState"));
config.JSONRecordFieldConfigurations.Add(new ChoJSONRecordFieldConfiguration("otherState", "$.otherState[*]") { FieldType = typeof(string[]) });
config.JSONRecordFieldConfigurations.Add(new ChoJSONRecordFieldConfiguration("createdAt"));
using (var r = ChoJSONReader.LoadText(json, config))
{
using (var w = new ChoCSVWriter(csv).WithFirstLineHeader()
.UseNestedKeyFormat(false)
)
w.Write(r);
}
Console.WriteLine(csv.ToString());
推荐阅读
- reactjs - 导入 ColorContrastChecker 在 ReactJS 中不起作用
- javascript - 高级 javascript 数组按计数分组
- c++ - 如何停止所有正在运行的线程并控制线程数?
- c# - 如何在 Azure Functions 中混合使用自定义参数绑定和依赖注入?
- google-app-maker - 我应该使用 App Maker 的服务器脚本、计算客户端还是关系来过滤数据以进行显示
- nativescript - Nativescript 6代码共享项目和tns-platform-declarations:编译时出错
- javascript - 将字符串转换为正则表达式时如何保留\
- c++ - 建立头文件和.cc文件之间的关系
- python-3.x - 复合赋值运算符的问题
- android - 我的图片库:prolog 中不允许有内容