我有一个类似这样的 JSON 文件:
{
"id": 2,
"name": "I.1.A.2",
"activeFlag": true,
"recipients": [
{
"id": 3,
"identityName": "idenity1",
"fullName": "FullName1"
},
{
"id": 4,
"identityName": "identity2",
"fullName": "FullName2"
}
]
}
我需要使用 C# 和 dotnet Core 将其转换为与此类似的 CSV 输出。
"id","name","activeFlag","identityName"
"2","I.1.A.2","true","identity1;identity2"
但是,我只能得到 CSV 输出:
"id","name","activeFlag","recipients_0", "recipients_1"
"2","I.1.A.2","true","identity1","identity2"
这是生成上述输出的代码:
using (var csv = new ChoCSVWriter(".\\temp\\csvoutput.csv").WithFirstLineHeader()
)
{
using (var json = new ChoJSONReader(".\\temp\\tmpjson.json")
.Configure(c => c.ConvertToFlattenObject(arrayIndexSeparator: ';'))
.Configure(c => c.ArrayValueSeparator = ';')
.Configure(c => c.ArrayValueSeparator = ';')
.WithField("id", jsonPath: "$..id", isArray: false)
.WithField("recipients", jsonPath: "$..recipients[*]..identityName", isArray: true, fieldName: "recipients")
)
{
csv.Write(json);
}
}
现在,我正在使用 ChoEtl 库,但愿意接受其他选项/建议。一直在寻找这个问题的答案,但还没有找到。抱歉,如果我还没有找到一些解决方案。我确实在这里尝试了类似的解决方案:How to output JSON array as a single field in CSV using ChoETL但不太能满足我的需求。
最佳答案
就我个人而言,我发现“投影”方法比基于配置的方法更容易使用和推理。请参阅https://www.codeproject.com/Articles/1193650/Cinchoo-ETL-Quick-Start-Converting-JSON-to-CSV-Fil
这对我有用:
using (var csv = new ChoCSVWriter(output).WithFirstLineHeader()) {
using (var json = new ChoJSONReader(input))
{
csv.Write(json.Select(jsonItem =>
{
var recipientList = new List<dynamic>(jsonItem.recipients);
string recipientString = string.Join(';', recipientList.Select(r => r.identityName));
return new
{
id = jsonItem.id,
name = jsonItem.name,
activeFlag = jsonItem.activeFlag,
identityName = recipientString
};
}));
}
}
可能有一种更优雅的方式来构造 identityName
的值,但由于这些值是动态的,因此很难直接使用 Linq 而不遇到 CS1977 错误。
但是,如果您更喜欢基于配置的方法,则可以将 valueConverter
与 jsonPath
结合使用,如下所示:
using (var csv = new ChoCSVWriter(output).WithFirstLineHeader())
{
using (var json = new ChoJSONReader(input)
.WithField("id")
.WithField("name")
.WithField("activeFlag")
.WithField("recipients", jsonPath: "$.recipients[*].identityName"
, valueConverter: o => string.Join(';', ((object[])o).Select(x => x.ToString())))
)
{
csv.Write(json);
}
}
我无法找到 ConvertToFlattenObject
的任何文档,因此我不确定它应该如何工作。
关于c# - 将 JSON 数组值合并到单个 CSV 列中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69168863/