Saturday, 2 March 2019

Generic way of Json to CSV converting for generic deep nested arrays

I am programing a function, that should convert generic deep nested JSON object levels to CSV file in JS or TypeScript. I tried several libraries but somehow they don't work the way i want it to unwind the nested JSON right. The code should unwind this input:

{
 [
  {
     app: "app1",
     device: [
       "c1",
       "c2",
       "c3",
       "c4"
     ]
   },
   {
     app: "app2",
     device: [
       "b1",
       "b2"
     ]
   }
 ]
}

Into this expected result:

app;device
app1;c1
app1;c2
app1;c3
app1;c4
app2;b1
app2;b2

Right now I'm using this code but the result is not like expected:

 private ConvertToCSV(json: string, fields: string[]): string {
    const Json2csvParser = require("json2csv").Parser;

    let options: {};

    options = { fields };

    const parser = new Json2csvParser(options);

    const csv = parser.parse(JSON.parse(json));
    console.log(JSON.parse(json));
    console.log(csv);
    return csv;
  }

My result right now looks like this:

"app","device"
"app1","[""c1"",""c2"",""c3"",""c4""]"
"app2","[""b1"",""b2""]"



from Generic way of Json to CSV converting for generic deep nested arrays

No comments:

Post a Comment