4

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

1 Answers1

2

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"}
  ]
});
Gonras Karols
  • 1,150
  • 10
  • 30
  • Yes I think that would work - would need to build the fields array first of course so it's an extra step, but not too onerous. As it turns out however for my particular use case (only converting to csv) it seems PapaParse is overkill, and I've managed to use https://github.com/evanplaice/jquery-csv to perform the conversion I need. However I think if using PapaParse and requiring 2-way conversion, then this solution is great. – stuffandting Feb 23 '17 at 12:43