【问题标题】:convert csv file data in json data将csv文件数据转换成json数据
【发布时间】:2014-04-14 21:11:12
【问题描述】:

我使用csvtojson转换器转换成json格式。

var csvFileName = path; //path== filepath

 var csvConverter = new Converter();

 csvConverter.on("end_parsed", function (jsonObj) {

 console.log('in json object', jsonObj);


   });



csvConverter.from(csvFileName);

我使用批量导出和导入 csv 文件中的数据。如果我只是导入 csv 文件而不更改导出的 csv 文件,那么 csvtojson 解析器会正确解析 json 格式的数据。就像

{ csvRows: 
   [ { id: '51f21e7c60c058bc54000001',
       name: 'dummy product',
       alias: 'dummy-product1111111111',
       description: 'Lorem Ipsumuuu',
       images: '',
       price: '55',
       compare_price: 'undefined',
       collections: 'undefined',
       brand: 'undefined',
       quantity: 'undefined',
       sku: 'undefined',
       barcode: 'undefined',
       categories: '',
       publish: '1',
       variants: undefined,
       state: undefined,
       avg_rating: undefined,
       num_reviews: undefined,
       weight: undefined,
       free_product: undefined,
       option_set: undefined }]

但是当我修改 csv 文件并导出然后 csvtojson parser parser data in this formate -

{ csvRows: 
   [ {  { 'id\tname\talias\tdescription\timages\tprice\tcompare_price\tcollections\tbrand\tquantity\tsku\tbarcode\tcategories\tpublish\tvariants\tstate\tavg_rating\tnum_reviews\tweight\tfree_product\toption_set': '525ba1b3f96404a56a000006\tbraclet12\tbraclet12\tundefined\t\t100\tundefined\tundefined\tundefined\tundefined\tundefined\tundefined\tundefined\t\t\t\t\t\t\t\t' }];

有什么办法可以将csv文件数据正确解析成json格式。

谢谢。

【问题讨论】:

    标签: javascript node.js


    【解决方案1】:

    您可以通过终端使用以下js文件。我认为这是不言自明的。如果没有,请写评论,我会解释。

    'use strict';
    
    var fs = require('fs'),
        args = process.argv.slice(2),
        seperator = ',',
        input = fs.readFileSync('input.csv', {encoding: 'UTF-8'}),
        lines = input.split('\n'),
        output = [],
        props = lines.shift().trim().split(seperator),
        i, j,
        values,
        obj;
    
    for (i = 0; i < args.length - 1; i++) {
        if (args[i] === '-s' || args[i] === '--seperator') {
            seperator = args[i + 1];
        }
    }
    
    for (i = 0; i < lines.length; i++) {
        if (lines[i].length > 0) {
            obj = {};
            values = lines[i].split(seperator);
            for (j = 0; j < props.length; j++) {
                obj[props[j]] = values[j];
            }
            output.push(obj);
        }
    }
    
    fs.writeFileSync('output.json', JSON.stringify(output), {encoding: 'UTF-8'});
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-13
      • 2019-09-11
      • 1970-01-01
      • 2015-01-22
      • 1970-01-01
      • 2014-11-23
      • 1970-01-01
      相关资源
      最近更新 更多