繁体   English   中英

在json数据中转换csv文件数据

[英]convert csv file data in json data

我使用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分析器分析器数据-

{ 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形式。

谢谢。

您可以通过终端使用以下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'});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM