如何在c#中将csv转换为json,而csv列有多个逗号分隔符?

时间:2017-11-09 11:22:04

标签: c#

我有一个csv文件,我需要在json中将该数据转换为json格式。我试图读取文件并获取数据,并用逗号(,)分隔符分割。然后将该数据转换为json格式。但结果并不是预期的结果。因为列值具有多个(,)分隔符。

任何人都可以帮我解决这个问题吗?

我的代码如下:

string targetFile = @"C:\Users\grajaji\Desktop\target.csv";
var csv = new List<string[]>(); 
var lines = System.IO.File.ReadAllLines(targetFile);

foreach (string line in lines)
      csv.Add(line.Split(',')); 

var json = JsonConvert.SerializeObject(csv);

return Request.CreateResponse(HttpStatusCode.OK, json);

结果是:

[["JOB ID","JOB NAME","ROLE DESCRIPTION/EXPECTATION","RESPONSIBILITIES","PREFERRED SKILLS PROFILE","JOB LOCATION","JOB START DATE","JOB STATUS","JOB OPEN DATE","ENGAGEMENT TYPE","FIXED PRICE (Y/N)","MILESTONE (Y/N)","HOURLY PAY (Y/N)","BUDGET CURRENCY (CURRENCY CODE)","BUDGET AMOUNT (NUMBER ONLY)","BILL CURRENCY (CURRENCY CODE)","BILL AMOUNT (NUMBERS ONLY)","TARGET SALARY CURRENCY (CURRENCY CODE)","TARGET SALARY AMOUNT (NUMBERS ONLY)","EDUCATION NAME","CERTIFICATION/LICENSURE","HIRING MANAGER","TALENT ADVISER","JOB CLUSTER KEYWORDS","CONTRACT TIME"],["","Operations Support Administrator","\"The Human Resources Operations Support Administrator is a critical member of the Human Resources team that serves approximately 62 schools and 5 administrative organizational units. The Operations Support Administrator will provide specialized"," technical support in one or more operational areas. The Operations Support Administrator will likely provide payroll and procurement support"," but will also provide support in one or more of the following operational areas: budgeting"," grants management"," contracts"," human resources"," technology"," school food"," transportation"," and/or health. The Operations Support Administrator�s specialty may vary from team to team and will depend on their prior experience.\"","\"Support a network of schools to continuously improve operations"," school support"," and customer service. Provide technical support and assistance related to assigned operational area(s). Manage systems associated with assigned operational area(s) and provide technical support to school-based staff as necessary. Collect and interpret test scores and other school performance data to help schools drive student achievement. Facilitate the preparation of statistical and narrative reports and/or visual presentations such as charts or graphs"," as appropriate. "],["Provide transactional oversight and support related to assigned operational area(s). Advocate/liaise with the district team"," the Human Resources team and central entities when necessary to ensure operational transactions are executed to meet compliance mandates and schools� satisfaction."],["Identify areas in which schools are in need of administrative and/or operational training and ensure that training opportunities are provided to each school."],["Provide guidance and resources to school-based personnel to increase the operational/administrative capacity and autonomy of each school. This includes frequent school visits to trouble-shoot and provide one-on-one support as necessary."],["Support Human Resources� service-oriented culture"," which is designed to attain high levels of principal satisfaction with the services and support the district provides."],["Provide critical"," technical operational information as available from Human Resources"," including central policy and process updates and changes."],["\"","\"Communcation Skills"," Attention to Detail"," DOE Systems"," Planning skills\"","\"New York","  New York"," USA\"","11-01-2017","OPEN","10-01-2017","CONTRACT","","","","USD","45000","USD","45000","USD","","Bachelor Degree","NYC Civil Service Status","John Jones","Carolina Smith","","6 months"]]

预期结果是:

[
  {
    "JOB ID": "",
    "JOB NAME": "Operations Support Administrator",
    "ROLE DESCRIPTION/EXPECTATION": "The Human Resources Operations Support Administrator is a critical member of the Human Resources team that serves approximately 62 schools and 5 administrative organizational units. The Operations Support Administrator will provide specialized, technical support in one or more operational areas. The Operations Support Administrator will likely provide payroll and procurement support, but will also provide support in one or more of the following operational areas: budgeting, grants management, contracts, human resources, technology, school food, transportation, and/or health. The Operations Support Administrator�s specialty may vary from team to team and will depend on their prior experience.",
    "RESPONSIBILITIES": "Support a network of schools to continuously improve operations, school support, and customer service. Provide technical support and assistance related to assigned operational area(s). Manage systems associated with assigned operational area(s) and provide technical support to school-based staff as necessary. Collect and interpret test scores and other school performance data to help schools drive student achievement. Facilitate the preparation of statistical and narrative reports and/or visual presentations such as charts or graphs, as appropriate. \nProvide transactional oversight and support related to assigned operational area(s). Advocate/liaise with the district team, the Human Resources team and central entities when necessary to ensure operational transactions are executed to meet compliance mandates and schools� satisfaction.\nIdentify areas in which schools are in need of administrative and/or operational training and ensure that training opportunities are provided to each school.\nProvide guidance and resources to school-based personnel to increase the operational/administrative capacity and autonomy of each school. This includes frequent school visits to trouble-shoot and provide one-on-one support as necessary.\nSupport Human Resources� service-oriented culture, which is designed to attain high levels of principal satisfaction with the services and support the district provides.\nProvide critical, technical operational information as available from Human Resources, including central policy and process updates and changes.",
    "PREFERRED SKILLS PROFILE": "Communcation Skills, Attention to Detail, DOE Systems, Planning skills",
    "JOB LOCATION": "New York,  New York, USA",
    "JOB START DATE": "11-01-2017",
    "JOB STATUS": "OPEN",
    "JOB OPEN DATE": "10-01-2017",
    "ENGAGEMENT TYPE": "CONTRACT",
    "FIXED PRICE (Y/N)": "",
    "MILESTONE (Y/N)": "",
    "HOURLY PAY (Y/N)": "",
    "BUDGET CURRENCY (CURRENCY CODE)": "USD",
    "BUDGET AMOUNT (NUMBER ONLY)": 45000,
    "BILL CURRENCY (CURRENCY CODE)": "USD",
    "BILL AMOUNT (NUMBERS ONLY)": 45000,
    "TARGET SALARY CURRENCY (CURRENCY CODE)": "USD",
    "TARGET SALARY AMOUNT (NUMBERS ONLY)": "",
    "EDUCATION NAME": "Bachelor Degree",
    "CERTIFICATION/LICENSURE": "NYC Civil Service Status",
    "HIRING MANAGER": "John Jones",
    "TALENT ADVISER": "Carolina Smith",
    "JOB CLUSTER KEYWORDS": "",
    "CONTRACT TIME": "6 months"
  }
]

1 个答案:

答案 0 :(得分:0)

简单的CSV解析器我真的不知道它会有多快。

    //You should allways reuse the regex objects since createing them can be slow
        private static readonly Regex regex = new Regex(",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");

        static void Main(string[] args)
        {
            //Some csv data
            var csv =
@"H1,H2,H3
1,""ASd, asdasd, asda"", asd
1,""ASd, asdasd, asda"", asd
1,""ASd, asdasd, asda"", asd";

            //Gets the lines from csv you can use the ReadAllLines
            var lines = csv.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);

            //In csv the first row can indicate the headers like in you case
            var headers = regex.Split(lines.First()).Select((name,index) => new { name, index });

            //Skip Header data and split the rest of the string
            var items = from line in lines.Skip(1)
                        let data = regex.Split(line)
                        select headers.ToDictionary(i => i.name, i=> data[i.index]);

            //Simple way to create JSON string can be optimised if you need high performance
            Console.WriteLine(JsonConvert.SerializeObject(items, Formatting.Indented));

            Console.ReadLine();
        }

但你真的应该发布原始的CSV,因为csv是非标准的。