Adding keys to existing json values

Viewed 62

I am converting a csv file into a json file with c# but the file I receive is just a bunch of values. I want to save them into a key => value format when converting to json.

My code:

static void ReadFromCsv()
    {
        var csv = new List<string[]>();
        var lines = System.IO.File.ReadAllLines(@"C:\path\details.csv");
        foreach (string line in lines)
            csv.Add(line.Split(','));
        var json = JsonSerializer.Serialize(csv);
        File.WriteAllText(@"C:\path2\jsontest.json", json);
    }

The json file ends up like this:

[
"20-7-2020",
"Ben",
"Smith",
"+27745004488",
"Orange",
"Tree",
"54 Victoria Road"
],
[   
"20-7-2020",
"Jade",
"Hodsin",
"+27743456060",
"Apple",
"Plant",
"20 Small Street"
]

My Goal is to make the json look like the following for easy storage into a sql DB:

[
"Date" : "20-7-2020",
"Name" : "Ben",
"Surname" : "Smith",
"Cell" : "+27745004488",
"Food" : "Orange",
"Source" : "Tree",
"Address" : "54 Victoria Road"
],
[   
"Date" : "20-7-2020",
"Name" : "Jade",
"Surname" : "Hodsin",
"Cell" : "+27743456060",
"Food" : "Apple",
"Source" : "Plant",
"Address" : "20 Small Street"
]
2 Answers

you need to read the header separately and join the header for the rest of the lines to a dictionary:

var csv = new List<Dictionary<string,string>>();
var lines = System.IO.File.ReadAllLines(@"C:\path\details.csv");
string[]header = lines[0].Split(',');

for (int i = 1; i < lines.Length; i++)
{
    string[] line = lines[i].Split(',');
    csv.Add(line.Zip(header, (value, key) => new { value, key })
                         .ToDictionary(x => x.key, x => x.value));
    
}

with a fixed header it would be easier:

string[] header = { "Date", "Name", "Surname", "Cell", "Food", "Source", "Address"};
foreach (string line in lines)
    csv.Add(line.Split(',').Zip(header, (value, key) => new { value, key })
                         .ToDictionary(x => x.key, x => x.value));

For me the best way to handle this situation id the make an object, you make the object the way you want to have your values and the you juste have to Serialize it. For my experience a well-made object in JS will Deserialize into a correct object in C#.

Plus this method can help you handle mistake from the incoming datas and avoid trouble deserializing problem, correctly check the data in JS can make you avoid many problems.

I guess you don't need the whole class to help you do the trick. Hope it've helped you a little. Have a nice day.

Related