Matt Darvell

Matt Darvell

  • 1.6k
  • 17
  • 1.5k

Creating a JSON File from a CSV file in C#

Oct 12 2023 12:22 PM

Apologies but this is going to be a "How to" question rather than a technical question. I am very new to C# and using Json. I have a CSV file as follows:

 

    Time             Control_Code    Metric    Organisation    Value    DateTime
    2018-10-21T00:08:03 JKX           3721      AD450          20   2018-10-21T00:08:00
    2018-10-21T00:08:03 BHY           1234      HG650          88   2018-10-21T00:08:00


I need to produce multiple JSON output files from that csv in the following format example:

    {
        "Time":"2018-10-21T00:08:03",
        "Control_Code": "JKX",
        "metrics": [
            {
                "Metric": 3721,
                "Organisation":"AD450",
                "Value": 20,
                "Datetime":"2018-10-21T00:08:00"
            },
            {
                "Metric": 1234,
                "Organisation":"HG650",
                "value": 88,
                "datetime":"2018-10-21T00:08:00"
            }
            
        ]
    }

Now the extra problematic part on top of this is that there is a requirement where only one Control_Code may be used per Json.
Each Json generated must contain a single Control_Code and all related metric values in the metrics array. So the csv will need to be scanned for each different Control_Code and then produce an output for that specific Control_Code and then do the same for any subsequent Control_Codes.

So for example a different Json would be produced with a different Control_Code (from the same csv file) - Example (notice different Control_Code other values will of course change as well, but just providing an example).

    {
        "Time":"2018-10-21T00:08:03",
        "Control_Code": "BHY",
        "metrics": [
            {
                "Metric": 3721,
                "Organisation":"AD450",
                "Value": 20,
                "Datetime":"2018-10-21T00:08:00"
            },
            {
                "Metric": 1234,
                "Organisation":"HG650",
                "value": 88,
                "datetime":"2018-10-21T00:08:00"
            }
            
        ]
    }

Thanks for any advice/information in advance.


Answers (2)