Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
345 views
in Technique[技术] by (71.8m points)

node.js - How to parse JSON object to CSV file using json2csv nodejs module

I'm currently learning how to parse a JSON object to a CSV file using the json2csv node module. Have never worked with JSON before, so this is all new to me.

My JSON object is formatted like this:

{
 "car":
      {
          "name":["Audi"],
          "price":["40000"],
          "color":["blue"]
      }
}

And the output CSV file is formatted like this:

"car","name","price","color"
{"name":["Audi"],"price":["40000"],"color":["blue"]},,,

How would I be able to get the CSV output to look like this instead?

name, price, color
"Audi",40000,"blue"

I understand I can call fields directly for just regular JSON data, but I don't understand how it would work under a JSON object.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

json2csv only support a flat structure where fields are direct children of the json root.

if you wish to change it, consider cloning the code and do something like the following:

// createColumnContent function changed from original code
var createColumnContent = function(params, str, callback) {
  params.data.forEach(function(data_element) {
    //if null or empty object do nothing
    if (data_element && Object.getOwnPropertyNames(data_element).length > 0) {
      var line = '';
      var eol = os.EOL || '
';
      params.fields.forEach(function(field_element) {
        // here, instead of direct child, getByPath support multiple subnodes levels
        line += getByPath(data_element, field_element.split('.'), 0) + params.del;
      });
      //remove last delimeter
      line = line.substring(0, line.length - 1);
      line = line.replace(/"/g, '""');
      str += eol + line;
    }
  });
  callback(str);
};

var getByPath = function(data_element, path, position) {
  if (data_element.hasOwnProperty(path[position])) {
    if (position === path.length - 1) {
      return JSON.stringify(data_element[path[position]]);
    }
    else {
      return getByPath(data_element[path[position]], path, position + 1)
    }
  }
  else {
    return '';
  }
}

usage:

json2csv({data: json, fields: ['car.name.0', 'car.price.0', 'car.color.0']}, function(err, csv) {
  if (err) console.log(err);
  fs.writeFile('file.csv', csv, function(err) {
    if (err) throw err;
    console.log('file saved');
  });
});

output file content:

"car.name.0","car.price.0","car.color.0"
"Audi","40000","blue"

as a side note, to clone and work with your own version:

git clone https://github.com/zeMirco/json2csv.git

add changes...

to use changed version:

npm install /local/path/to/repo

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...