简体   繁体   中英

C# how to convert json to CSV

I want to write a program to convert the json to CSV But it has problem to convert CSV because I have the column name including an array, when I use my function to convert, it has the problem For example: Here is my json that want to convert:

{  
   "ref":"ABC123456",
   "pickcompname":"ABC Company",
   "gw":123.45,
   "packaing":[  
      {  
         "qty":5,
         "unit":"C",

      },
      {  
         "qty":7,
         "unit":"L",

      }
   ]
}

But I want to make the Packaing can convert the column name such as qty1,unit1,qty2,unit2, Unfortunately, it only output:

"ref",
"pickcompname",
"gw",
"commoditytype",
"packaing""ABC123456",
"ABC Company",
"123.45",
"D",
"[
    {
        "qty":5,
        "unit":"C"
    },
    {  
    "qty":7,
    "unit":"L",
    }
]"

How to I modify it and Here is my C# code:

    public string JsonToCsv3(string jsonContent, string delimiter)
    {

        var data = jsonStringToTable(jsonContent);
        var headers = ((IEnumerable<dynamic>)((IEnumerable<dynamic>)data).First()).Select((prop) => prop.Name).ToArray();
        var csvList = new List<string> 
        {
            string.Join(delimiter, headers.Select((prop) => string.Format(@"""{0}""", prop)).ToArray())
        };

        var lines = ((IEnumerable<dynamic>)data)
            .Select(row => row)
            .Cast<IEnumerable<dynamic>>()
            .Select((instance) => string.Join(delimiter, instance.Select((v) => string.Format(@"""{0}""", v.Value))))
            .ToArray();

        csvList.AddRange(lines);
        return string.Join(Environment.NewLine, csvList );
    }


    static private dynamic jsonStringToTable(string jsonContent)
    {
        var json = jsonContent.Split(new[] { '=' }).Last();
        return JsonConvert.DeserializeObject<dynamic>(json);
    }

    static private IEnumerable<T> jsonStringToTable<T>(string jsonContent) where T : class
    {
        var json = jsonContent.Split(new[] { '=' }).Last();
        return JsonConvert.DeserializeObject<IEnumerable<T>>(json);
    }

Here is how you can do it with Cinchoo ETL

using (var p = new ChoJSONReader("sample16.json")
    .WithField("Ref", jsonPath: "$..ref", fieldType: typeof(string))
    .WithField("pickcompname", jsonPath: "$..pickcompname", fieldType: typeof(string))
    .WithField("gw", jsonPath: "$..gw", fieldType: typeof(double))
    .WithField("qty1", jsonPath: "$..packaing[0].qty", fieldType: typeof(int))
    .WithField("unit1", jsonPath: "$..packaing[0].unit", fieldType: typeof(string))
    .WithField("qty2", jsonPath: "$..packaing[1].qty", fieldType: typeof(int))
    .WithField("unit2", jsonPath: "$..packaing[1].unit", fieldType: typeof(string))
    )
{
    using (var c = new ChoCSVWriter("sample16.csv").WithFirstLineHeader())
        c.Write(p);
}

Output:

Ref,pickcompname,gw,qty1,unit1,qty2,unit2
ABC123456,ABC Company,123.45,5,C,7,L

Taking only a dependency on Newtonsoft.Json, here's a helper method given an array of CSV lines, the first one being the header.

    public static IEnumerable<JObject> CsvToJson(IEnumerable<string> csvLines)
    {
        var csvLinesList = csvLines.ToList();

        var header = csvLinesList[0].Split(',');
        for (int i = 1; i < csvLinesList.Count; i++)
        {
            var thisLineSplit = csvLinesList[i].Split(',');
            var pairedWithHeader = header.Zip(thisLineSplit, (h, v) => new KeyValuePair<string, string>(h, v));

            yield return new JObject(pairedWithHeader.Select(j => new JProperty(j.Key, j.Value)));
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM