zemirco / json2csv

Convert json to csv with column titles
http://zemirco.github.io/json2csv
MIT License
2.71k stars 365 forks source link

Reading external json files #135

Closed nickk75 closed 8 years ago

nickk75 commented 8 years ago

Hey guys,

Quick question I tried to import data from an external json file; as it is a large record, in my JS script as shown below.

var json2csv = require('json2csv');
var fs = require('fs');
var fields = ['occupationGroup', 'occupationCode', 'OccupationName'];
var fieldNames = ['occupationGroup', 'occupationCode', 'OccupationName'];

var occupations = fs.readFileSync('./occupations.json', 'utf8');
var opts = {
    data: occupations,
    fields: fields,
    fieldNames: fieldNames
};
var csv = json2csv(opts);

fs.writeFile('file.csv', csv, function(err) {
  if (err) throw err;
  console.log('file saved');
});

I have this code written (bear in mind, I'm new to JS and programming in general), it executes successfully (no syntactical errors) but there are no outputs in the csv file. Any chance someone can lend me a hand with it?

PS, below is an example of some of the json file entries, they are homogeneous, with 3 key:value objects per entry.

{
    "occupationGroup" : "Service occupations",
    "occupationCode" : "823121",
    "occupationName" : "Outdoor cleaning staff"
}
{
    "occupationGroup" : "Service occupations",
    "occupationCode" : "823121",
    "occupationName" : "Parking employee"
}
{
    "occupationGroup" : "Service occupations",
    "occupationCode" : "823121",
    "occupationName" : "Waste recovery industry"
}

Thank you in advance,

Nikos.

knownasilya commented 8 years ago

After you read the file in that manner, you still need to JSON.parse(..) since the contents are a string. I'd recommend var occupations = require('./occupations.json'); instead.

nickk75 commented 8 years ago

Hey Guys,

Thanks for the help, I was doing a few things wrong to begin with. I was passing an array of elements, and wasn't referencing the root element, therefore the rest of the array wasn't been passed down. I knew you can reference json files directly with the require function, but wasn't working for me previously, but it's all good now. Thanks for the help knownasilya, much appreciated and thanks for the library.

One love,

Nikos.

knownasilya commented 8 years ago

Can you upload your json to a gist or something so I can test? Thanks!