-2

I have converted CSV to a list of string I want to create a JSON using the header of CSV file the input and output are as mentioned below

var list = [
    [a,b,c],
    [1,2,3],
    [4,5,6]
    ];

to

var json = { 
        {
            "a":1,
            "b":2,
            "c":3
        },
        {
            "a":4,
            "b":5,
            "c":6
        }
    }
Drag and Drop
  • 2,672
  • 3
  • 25
  • 37
  • If the "header" elements are unique, perhaps you could construct a `Dictionary` for each row. – ProgrammingLlama Apr 13 '21 at 06:46
  • ref here : https://stackoverflow.com/questions/9110724/serializing-a-list-to-json – Vinoth Rajendran Apr 13 '21 at 06:46
  • 4
    `var list = [ [a,b,c], [1,2,3], [4,5,6] ]` is an invalid object, whats the actual data youre working with? – Simon Price Apr 13 '21 at 06:52
  • 1
    Also, that JSON isn't valid because you have an object directly containing objects with no properties. – ProgrammingLlama Apr 13 '21 at 06:52
  • [ask], and [mre] will help clarify this question. An input and output is not enought to create a question. You should have basic description, explaining the step etc. Here you have an other issue neither your input nor your ouput seems correct. You should perhaps read https://www.json.org/json-en.html too. and check the json representation for Array. Are you sure you want to project a List of dictionary where the key are the first "row" of the 2d array? – Drag and Drop Apr 13 '21 at 06:59
  • From my understanding you want to convert a Csv to json. Perhaps CsvHelper is what you need. Read the Csv to a list of custom Object. and serialize that object that will be 3 lines of code.. – Drag and Drop Apr 13 '21 at 06:59
  • Does this answer your question? [Serializing a list to JSON](https://stackoverflow.com/questions/9110724/serializing-a-list-to-json) – Pac0 Apr 13 '21 at 07:00

2 Answers2

0

Assuming your list looks like

        var list = new string[3][] {
            new string[3] { "a","b","c" },
            new string[3] {"1","2","3" },
            new string[3] {"4","5","6"}
        };

You can make a json from it using this method:

public static string toJson(string[][] csvArray) {
        var sb = new StringBuilder("{\n\"elements\": [\n");
        var headers = new string[csvArray[0].Length];
        
        for(int i = 0; i < csvArray[0].Length; i++)
        {
            headers[i] = csvArray[0][i];
        }
        
        for(int i = 1; i < csvArray.Length; i++)
        {
            sb.AppendLine("{");
            for(int j = 0; j < csvArray[i].Length; j++)
            {
                sb.AppendLine("\"" + headers.ElementAtOrDefault(j) + "\": \"" + csvArray[i][j] + "\",");
            }
            sb.Remove(sb.Length-3, 3); // remove last ",/n" to make json valid
            sb.AppendLine("\n},");
        }
        sb.Remove(sb.Length-3, 3); // remove last ",/n" to make json valid
        sb.AppendLine("\n]\n}");
        
        return sb.ToString();
    }

Check it in fiddler. Some alterations might be needed to adjust to your input data, maybe some additional validations, but it will let you go forward.

Andrii
  • 133
  • 1
  • 10
0

Using CSV Helper you can deserialize to Dynamic, ref doc.

Then you can serialize the result to json using JSON.Net ref.

var txtInput = "a,b,c\n1,2,3\n4,5,6";
string output;
using (var reader = new StringReader(txtInput))
using (var csvReader = new CsvReader(reader, CultureInfo.InvariantCulture))
{
    var records = csvReader.GetRecords<dynamic>();
    output = JsonConvert.SerializeObject(records, Formatting.Indented);
}

Result:

[
  {
    "a": "1",
    "b": "2",
    "c": "3"
  },
  {
    "a": "4",
    "b": "5",
    "c": "6"
  }
]

Live Demo : https://dotnetfiddle.net/lF0zJ2


Note that for CSV file you can use a StreamReader like :

using (var reader = new StreamReader("path\\to\\file.csv"))

While I don't recommend using dynamic typing. For reading a CSV I will recommend writing the proper class representing the data and the mapping class in order to let CSV Helper do everything: type check, unordered column, missing column, missing header, duplicate name column, different separator, multiline data, quoted field etc etc.

Disclaimer:
This answers doesn't match the given input and ouput. I choosed to take into account only the part that was valid. If you need the ouput to be int instead of string. You can create a class representing the Csv Object (CSV helper Getting Started ). And use csvReader .GetRecords<MyClass>().

Self
  • 349
  • 1
  • 8