Search code examples
javascriptcsvpapaparse

Can the PapaParse "unparse" function work with varying headers?


I'm trying to use the PapaParse library (http://papaparse.com/) to convert JavaScript objects/JSON into a CSV file. Specifically in my case, each record may have different fields. I want the resulting CSV output to be an agregate of all fields for a given record. Take the JSON below: -

[

 {"name":"ken",
  "age":"35"},

 {"name":"joe",
  "age":"37",
  "shoe_size":"12"},

 {"name":"fred",
  "age":"26",
  "favourite_colour":"blue"}

]

You will see that "fred" has a "favourite_colour", and "joe" has a "shoe_size", and they all have a name and age.

If I paste that code into here: https://konklone.io/json/

I get something like this: -

name    age shoe_size   favourite_colour
ken     35      
joe     37  12  
fred    26              blue

Essentially it parses the entire data set, and populates each header if it exists, which is what I want. However, if I use the PapaParse function: -

Papa.unparse('[{"name":"ken","age":"35"},{"name":"joe","age":"37","shoe_size":"12"},{"name":"fred","age":"26","favourite_colour":"blue"}]',{type:"text/csv;charset=utf-8"});

I get: -

name    age
ken     35
joe     37
fred    26

So it appears that the Papa.unparse() function is only taking note of the headers in the first record, and ignoring any records that occur subsequently.

I know that in theory I could fudge it by making sure the 1st record has every field, even if it's blank, but wondered whether there was a feature/option that would make it work this way without such persuasion?

Thanks


Solution

  • I think you could pass the fields explicitly to unparse, like this:

    var csv = Papa.unparse({
    fields: ["name", "age", "shoe_size", "favourite_color"],
    data: [
    
     {"name":"ken",
      "age":"35"},
    
     {"name":"joe",
      "age":"37",
      "shoe_size":"12"},
    
     {"name":"fred",
      "age":"26",
      "favourite_colour":"blue"}
      ]
    });