0

Here is a nice example on how to convert a complete json to csv.

I installed the program using npm install json-2-csv

I tried to take a run at the example. I made a js file but I can't run it. How can I run it to see in action how it works?

It is the example provided for json-2-csv page.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8"/>
        <title> </title>
    </head>

    <body>

    <script>
    var converter = require('json-2-csv');

var documents = [
    {
        Make: 'Nissan',
        Model: 'Murano',
        Year: '2013',
        Specifications: {
            Mileage: '7106',
            Trim: 'S AWD'
        }
    },
    {
        Make: 'BMW',
        Model: 'X5',
        Year: '2014',
        Specifications: {
            Mileage: '3287',
            Trim: 'M'
        }
    }
];

var json2csvCallback = function (err, csv) {
    if (err) throw err;
    console.log(csv);
};

converter.json2csv(documents, json2csvCallback);

    </script>

    </body>

</html>
Community
  • 1
  • 1
Robbbbbi
  • 59
  • 1
  • 2
  • 10

2 Answers2

1

Assuming you have node and npm installed...

You need to forget about the HTML markup. That's what node is complaining about.

  • Create a folder called something like example.
  • In that folder, run npm install json-2-csv.
  • Create a file called example.js and paste in the following. Basically, just the script from your question...

var converter = require('json-2-csv');

var documents = [
    {
        Make: 'Nissan',
        Model: 'Murano',
        Year: '2013',
        Specifications: {
            Mileage: '7106',
            Trim: 'S AWD'
        }
    },
    {
        Make: 'BMW',
        Model: 'X5',
        Year: '2014',
        Specifications: {
            Mileage: '3287',
            Trim: 'M'
        }
    }
];

var json2csvCallback = function (err, csv) {
    if (err) throw err;
    console.log(csv);
};

converter.json2csv(documents, json2csvCallback);
  • Save the file in that folder.
  • In that folder, run node example.js.

That's it! The program will print out the data in CSV format.

Brent Rockwood
  • 745
  • 4
  • 7
0

Assuming your file is called myFile.js, run the following from terminal in the same directory as your JS file:

node myFile.js

This assumes you've installed NodeJS which you can install from NodeJS.org.

Brant
  • 1,764
  • 11
  • 18
  • Yes I got the nodejs but when I run the command it gives me back SyntaxError: Unexpected token < Could be possible to provide a full example? How my js file have to be, what steps should I do and how to save the results to a new csv file? – Robbbbbi Jan 28 '15 at 19:20
  • Can you post your JS code so we can look at it? Tough to see your syntax error without. – Brant Jan 28 '15 at 19:22