简体   繁体   中英

What csv format is for json array, and how to convert them into json array, Nodejs

Good day, I been searching for a few hours and couldn't find the result that I want. First of all, I do not know how does a CSV looks like with the following JSON array.

[
  { email: "test@test.com",
    contactNo: "123456",
    meta: [
         {key: "Name", value: "Kevin XYZ", type: "string"},
         {key: "Position", value: "Chairman", type: "string"}]
  }
]

What's the csv format for the following json array, and how to convert them from csv to json array in NodeJS.

think of your CSV file just like an Excel sheet, where you only have Columns and Rows, so with your preferred structure, you need to define at least these columns:

|| email || contactNo || name || position ||

Those 4 are the most basic header columns your CSV needs, then you'll need a transformer function to handle the data structure you want.

In my experience, I'm using https://www.papaparse.com/ for the CSV Parser, you can have a look at the sample and try it yourself.

In your case, the parser function would be like this:

 const parsed = await Papa.parse(csvString, { header: true, trimHeaders: true, skipEmptyLines: 'greedy', transformHeader: val => isString(val)? trimAll(val): val, transform: (val, headerName) => { return isString(val)? trimAll(val): val } }); // [ { "email": "user1@user.com", "contactNo": "1234-5678", "name": "Doe", "position": "doctor", }, { "email": "user2@user.com", "contactNo": "1234-5678", "name": "John", "position": "developer" }, ... ]

Cheers,

This is the csv format to your JSON structure.you can use this Online converter to see how your csv look like.

CSV

This is how you can convert the csv to JSON. You can refer this good tutorial to learn how to convert the csv to JSON format. The function which is used there is below.

function csvJSON(csv){

    var lines=csv.split("\n");

    var result = [];

    var headers=lines[0].split(",");

    for(var i=1;i<lines.length;i++){

        var obj = {};
        var currentline=lines[i].split(",");

        for(var j=0;j<headers.length;j++){
            obj[headers[j]] = currentline[j];
        }

        result.push(obj);

    }


    return JSON.stringify(result); //JSON
}

You can use json2csv npm module http://www.mircozeiss.com/json2csv/

I found out that using npm csvtojson is much easier.

CSV:

email, contactNo, meta.0.key, meta.0.value, meta.0.type, meta.1.key, meta.1.value, meta.1.type
test@test.com, 12345, Name, Kevin XYZ, string, Position, Chairman, string
test1@test.com, 321433, Name, John ABC, string, Position, Accountant, string

by using the following code:

const csv = require('csvtojson');

const csvStr = "The csv above"

csv()
  .fromString(csvStr)
  .subscribe((jsonObj) => {
    console.log(jsonObj);
  });

The result of the json will be:

{ email: 'test@test.com',
  contactNo: '12345',
  meta:
   [ { key: 'Name', value: 'Kevin XYZ', type: 'string' },
     { key: 'Position', value: 'Chairman', type: 'string' } ] }
{ email: 'test1@test.com',
  contactNo: '321433',
  meta:
   [ { key: 'Name', value: 'John ABC', type: 'string' },
     { key: 'Position', value: 'Accountant', type: 'string' } ] }

In conclusion, using the header xx.0.yy is not so user friendly, I recommend just using what Duc Hong said.. header: email, contactNo, Name, Position and transform to the format that you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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