-1

right now I'm having a nested JSON tree object (this.props.holdinginfo) sending from backend to frontend, and I am trying to add an EXPORT button on the webpage to be able to export the JSON object to a csv file using react.

The JSON tree object is as below:

[{'holder': 'Passive', 'Position': 500.0, 'pct_shares_out': 0.5,
    'Node': [{'holder': 'TD Inc.', 'Position': 300.0, 'pct_shares_out': 0.2,
            'Node': [{'holder': 'TD ETF', 'Position': 400, 'pct_shares_out': 0.1}, 
                 {'holder': 'TD Fund', 'Position': 430.0, 'pct_shares_out': 0.2}]}, 
 {'holder': 'Active', 'Position': 725.0, 'pct_shares_out': 0.1, 
    'Node': [{'holder': '18 Asset', 'Position': 390, 'pct_shares_out': 0.5, 
            'Node': [{'holder': '18 Inc.', 'Position': 190, 'pct_shares_out': 0.2}, 
                 {'holder': 'Lysander-18 Equity Fund Series A', 'Position': 19, 'pct_shares_out': 0.05}]}]}];

And I want the csv file following the format below:

holder/position/pct_share_out
'Passive'/500.0/0.5
'TD Inc.'/300.0/0.2
'TD ETF'/400/0.1
'TD Fund'/430/0.2
'Active'/725/0.1
'18 Asset'/390/0.5
'18 Inc.'/190/0.2
'Lysander-18 Equity Fund Series A'/19/0.05 

What I am doing right now is adding a button in js file in component:

<Button variant="contained" 
    size="small" 
    onClick={this.handleExport}>
    <SaveIcon label="Export" />
        Export
</Button>

which calls handleExport to export the table into a csv file:

handleExport = () => {
    let csv = Papa.unparse(this.props.holdinginfo);
    console.log(csv);
}

But since this.props.holdinginfo is a nested tree object, the output of console.log is ""[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object].... "

Question I have - 1- How to convert the nested tree JSON into csv? 2- How to download that csv when the user click the button?

Thanks for helping!!

csmasterjk
  • 25
  • 1
  • 5
  • hey as i'm new to react, do u have any sample code I can have a look? – csmasterjk Jul 03 '19 at 21:42
  • It's really nothing to do with react, just pure JavaScript. I'll try to work up an example soon – Mark Jul 03 '19 at 21:48
  • See [ https://stackoverflow.com/questions/8847766/how-to-convert-json-to-csv-format-and-store-in-a-variable ]. I think it will help you unless you insist on using React. – Ivan Ganchev Jul 03 '19 at 22:00
  • You didnt stipulate the javascript framework you are using.... and You would have asked what library convert json to csv... or you create the library yourself and add to your Resume – Declan Nnadozie Jul 03 '19 at 22:01

4 Answers4

0

I would first convert the json object into a list first, i would create a recursive function that parses through the elements, every time it finds an attribute it just appends its value, but if it finds an object or array call the recursive function which should return a list of elements to append to the main list, or instead of returning a list you can return a string, building the string during the recursion. Another option i would consider is to create a recursive function to convert the multilevel json object to a plain json object, passing the json object through the recursions, in each recursion adding the attributes of the current level, and then convert it to whatever i need. Of course i would try those only if i didn't find a library or function that does it automatically.

0

You can't call papa.unparse because you don't have a flat array. Your data structure is recursive, so you'll need a recursive function to flatten if before sending it to papa.unparse.

const j = [{'holder': 'Passive', 'Position': 500.0, 
'pct_shares_out': 0.5,                          
'Node': [{'holder': 'TD Inc.', 'Position': 300.0, 'pct_shares_out': 0.2,                                
'Node': [{'holder': 'TD ETF', 'Position': 400, 'pct_shares_out': 0.1},                               
{'holder': 'TD Fund', 'Position': 430.0, 'pct_shares_out': 0.2}]},
{'holder': 'Active', 'Position': 725.0, 'pct_shares_out': 0.1,                                     
'Node': [{'holder': '18 Asset', 'Position': 390, 'pct_shares_out': 0.5,                                 
'Node': [{'holder': '18 Inc.', 'Position': 190, 'pct_shares_out': 0.2},                              
{'holder': 'Lysander-18 Equity Fund Series A', 'Position': 19, 'pct_shares_out': 0.05}]}]}]}];

const papa = require('papaparse');                                                               
function flatten(array) {                           
        var result = [];                                
        array.forEach(function (a) {                        
        var node = a.Node;
        delete a.Node;
        result.push(a);
        if (node) {
            result = result.concat(flatten(node));
        }
    });
    return result;
}
const flat = flatten(j);
console.log(flat)
console.log(papa.unparse(flat));

Mark
  • 867
  • 4
  • 8
0
  1. get the json file from the backend..
  2. import this module pass your json to it
  3. then as for user being able to download your csv.... check here
Declan Nnadozie
  • 1,026
  • 8
  • 18
0

To get into a simple list, a recursive function can be used similar to below:

const input = [{
  'holder': 'Passive',
  'Position': 500.0,
  'pct_shares_out': 0.5,
  'Node': [{
      'holder': 'TD Inc.',
      'Position': 300.0,
      'pct_shares_out': 0.2,
      'Node': [{
          'holder': 'TD ETF',
          'Position': 400,
          'pct_shares_out': 0.1
        },
        {
          'holder': 'TD Fund',
          'Position': 430.0,
          'pct_shares_out': 0.2
        }
      ]
    },
    {
      'holder': 'Active',
      'Position': 725.0,
      'pct_shares_out': 0.1,
      'Node': [{
        'holder': '18 Asset',
        'Position': 390,
        'pct_shares_out': 0.5,
        'Node': [{
            'holder': '18 Inc.',
            'Position': 190,
            'pct_shares_out': 0.2
          },
          {
            'holder': 'Lysander-18 Equity Fund Series A',
            'Position': 19,
            'pct_shares_out': 0.05
          }
        ]
      }]
    }
  ]
}];


var result = [];

function toCSV(items) {
  if (items) {
    items.forEach(function(a) {
      result.push({
        0: a.holder,
        1: a.Position + '/' + a.pct_shares_out
      });
      toCSV(a.Node);
    });
  }
}
  toCSV(input);
console.log(result)

It may be modified, as per requirement and use in papaparse.

Vishnu
  • 1,881
  • 1
  • 24
  • 45