ChoETL json to csv with multiple arrays

380 Views Asked by At

If I have a sample json like this and I want to use choETL to convert json to csv, how do i write both arrays to one file?

{
  "Id": "123456",
  "Request": [
    {
      "firstName": "A",
      "lastName": "B",
    }
  ],
  "Response": [
    {
      "SId": "123"
    }
  ]
}

Csv file should be something like Id,firstName,lastName,SId 123456,A,B,123

1

There are 1 best solutions below

6
On

Here is how you can produce the expected CSV from the json by using ChoETL

using (var r = ChoJSONReader.LoadText(json)
       .WithField("Id")
       .WithField("firstName", jsonPath:"Request[0].firstName", isArray:false)
       .WithField("lastName", jsonPath:"Request[0].lastName", isArray:false)
       .WithField("SId", jsonPath:"Response[0].SId", isArray:false)
       )
{
    using (var w = new ChoCSVWriter(Console.Out).WithFirstLineHeader())
        w.Write(r);
}

Output:

Id,firstName,lastName,SId
123456,A,B,123

Sample fiddle: https://dotnetfiddle.net/CnBX3C

UPDATE:

If the array is dynamic, here is one way to produce the CSV output by Request json array field

Sample JSON:

{
  "Id": "123456",
  "Request": [
    {
      "firstName": "A",
      "lastName": "B",
    },
    {
      "firstName": "A1",
      "lastName": "B1",
    }
    ],
  "Response": [
    {
      "SId": "123"
    },
    {
      "SId": "1234"
    }
  ]
}

Here is the code to parse the json by Request json array field

using (var r = ChoJSONReader.LoadText(json)
       .Configure(c => c.FlattenNode = true).Configure(c => c.FlattenByNodeName = "Request")
       )
{
    using (var w = new ChoCSVWriter(Console.Out).WithFirstLineHeader())
        w.Write(r);
}

Output:

Id,Response_0_SId,Response_1_SId,RequestfirstName,RequestlastName
123456,123,1234,A,B
123456,123,1234,A1,B

Sample fiddle: https://dotnetfiddle.net/CnBX3C