1

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 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

6 Comments

what if the array is dynamic?
depends how the csv file to be produced. pls provide sample expected csv file.
here is one approach dotnetfiddle.net/ya6Sjf
Thanks for your response i think the requirement was much simpler than originally thought, so i was able to get it to work with most of the samples available
use .Configure(c => c.FileHeaderConfiguration.QuoteAllHeaders = true) on CSVWriter to writer headers with quotes.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.