Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
394 views
in Technique[技术] by (71.8m points)

CsvHelper - Custom parser for a certain column

Is therer a good way to override the parsing for a certain column/field i.e. for not well-formatted documents containing a json object. Stream reading json & therby moving stream forward past the incorrect/malformatted csv field but also saving/returning json.

Preferable in combination CsvDataReader & DataTable.Load

Edit - clarify sample:
col_a;col_b;col_c;col_json
0.0;-1;0;{"t": 1598270895, "text": "hello world" }

question from:https://stackoverflow.com/questions/65850313/csvhelper-custom-parser-for-a-certain-column

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I don't think this is supposed to work, but I did find that just setting BadDataFound = null worked with the latest version of CsvHelper and your example data.

It doesn't, however, work if "text" has line breaks or semicolon in it.

void Main()
{
    var config = new CsvConfiguration(CultureInfo.InvariantCulture)
    {
        BadDataFound = null,
        Delimiter = ";"
    };
    using(var reader = new StringReader("col_a;col_b;col_c;col_json
0.0;-1;0;{"t": 1598270895, "text": "hello world"}"))
    using(var csv = new CsvReader(reader, config))
    {
        using (var dr = new CsvDataReader(csv))
        {
            var dt = new DataTable();
            dt.Load(dr);
            dt.Dump();
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...