使用自定义头Javascript将JSON转换为CSV,将CSV转换为JSON



我正在努力寻找一种在没有外部库的情况下实现支持csv格式的导入/导出功能的好方法。任何能在这方面帮助我的人都是救命稻草。真正地

我有一个csv字符串,我将其称为"csv";A":

"First Name,Last Name,Phone NumberrnJohn,Doe,0102030405rnJoe,Dohn,0102030406"

我有一个json数组,我将其称为"json";B":

[
{
firstName: "John",
lastName: "Doe",
phone: "0102030405"
},
{
firstName: "Joe",
lastName: "Dohn",
phone: "0102030406"
}
]
  • 我需要创建一个通用函数,该函数接受一个定义从a到B的头的对象数组
  • 我还需要创建一个通用函数,它接受一个定义头的对象数组,从B到a

在这种特定情况下,定义标头的对象数组如下所示:

[
{
label: "First Name",
key: "firstName",
},
{
label: "Last Name",
key: "lastName",
},
{
label: "Phone Number",
key: "phone",
}
]

编辑:我的实际数据有点不同,Darshan Jain的解决方案并不完全有效(导入效果很好,但导出效果不好(。这是我的json,它实际上是猫鼬集合的一个元素:

[
{
auxiliaryActionZones: [],
backOfficePrivateNotes: [],
_id: 60003b0ac20b224a58976294,
id: 'acf7660c-4277-4b40-8e99-c00445daf755',
status: 'Candidat',
innactivityStartDate: null,
innactivityEndDate: null,
firstName: 'Marcus',
lastName: 'CASTO',
dateOfBirth: null,
avatarURI: '',
phone: '+33601020304',
email: 'marcus@gmail.com',
address1: 'Rue de Paradis',
address2: '',
city: 'Paris',
postalCode: '75010',
location: '',
companyLegalStatus: 'Auto-entrepreneur',
companyAddress1: 'Some address',
companyAddress2: '',
companyCity: 'Paris',
companyPostalCode: '75000',
companyLocation: '',
companyName: 'Entreprise CASTO',
companySiren: '',
companyInstitutionCode: '',
companyKbisURI: '',
companyNic: '',
companyRcs: '',
companyHasVAT: true,
companyIntracomVATCode: '',
companyVATRate: '',
bic: '',
iban: '',
contractURI: '',
contractAppendicesURI: '',
billingMandateURI: '',
selfBillingMandateURI: '',
insurancePolicyURI: '',
doesBirthShootings: false,
doesBabyAndChildrenShootings: false,
doesFamilyShootings: false,
doesPregnancyShootings: false,
doesNurseryAndSchoolShootings: false,
experienceYears: '',
canShootAtClientHome: false,
canShootOutside: false,
canShootInStudio: false,
website: '',
instagram: '',
facebook: '',
hasDigitalReflex: false,
hasCobraFlash: false,
hasStudioKit: false,
hasPregnancyAccessories: false,
hasBirthAccessories: false,
cameras: '',
lens: '',
selfPresentation: '',
additionalComment: '',
availableTime: '',
isMovingByFoot: false,
isMovingByBicycle: false,
isMovingByPersonalVehicle: false,
isMovingByPublicTransportation: false,
actionZone: 10,
creationDate: 2021-01-14T12:37:30.862Z,
lastModificationDate: 2021-01-14T12:37:30.862Z,
applicationValidationDate: null,
memberAcceptanceDate: null,
__v: 0
},
]

当我尝试导出它时,它会给出以下标题:

[
{
label: 'Identifiant',
key: 'id'
},
{
label: 'Statut',
key: 'status'
},
{
label: 'Date de début d'innactivité',
key: 'innactivityStartDate'
},
{
label: 'Date de fin d'innactivité',
key: 'innactivityEndDate'
},
{
label: 'Prénom',
key: 'firstName'
},
{
label: 'Nom',
key: 'lastName'
},
{
label: 'Date de naissance',
key: 'dateOfBirth'
},
{
label: 'Mobile',
key: 'phone'
},
{
label: 'Email',
key: 'email'
},
{
label: 'Mot de passe',
key: 'password'
},
{
label: 'Confirmation de mot de passe',
key: 'passwordConfirmation'
},
{
label: 'Adresse ligne 1',
key: 'address1'
},
{
label: 'Adresse ligne 2',
key: 'address2'
},
{
label: 'Adresse Code postal',
key: 'postalCode'
},
{
label: 'Adresse Ville',
key: 'city'
},
{
label: 'Localisation',
key: 'location'
},
{
label: 'Type structure',
key: 'companyLegalStatus'
},
{
label: 'Nom entreprise',
key: 'companyName'
},
{
label: 'Entreprise ligne 1',
key: 'companyAddress1'
},
{
label: 'Entreprise ligne 2',
key: 'companyAddress2'
},
{
label: 'Entreprise Code postal',
key: 'companyPostalCode'
},
{
label: 'Entreprise Ville',
key: 'companyCity'
},
{
label: 'Entreprise Localisation',
key: 'companyLocation'
},
{
label: 'Siren',
key: 'companySiren'
},
{
label: 'Code établissement',
key: 'companyInstitutionCode'
},
{
label: 'Soumis à la TVA',
key: 'companyHastVAT'
},
{
label: 'Taux TVA',
key: 'companyVATRate'
},
{
label: 'Code TVA Intracommunautaire',
key: 'companyIntracomVATCode'
},
{
label: 'BIC',
key: 'bic'
},
{
label: 'IBAN',
key: 'iban'
},
{
label: 'Contrat',
key: 'contractURI'
},
{
label: 'Annexes contrat',
key: 'contractAppendicesURI'
},
{
label: 'Police d'assurance',
key: 'insurancePolicyURI'
},
{
label: 'Mandat d'autofacturation',
key: 'selfBillingMandateURI'
},
{
label: 'Entreprise Localisation',
key: 'companyLocation'
},
{
label: 'Expérience Naissance',
key: 'doesBirthShootings'
},
{
label: 'Expérience BB/Enfant',
key: 'doesBabyAndChildrenShootings'
},
{
label: 'Expérience Famille',
key: 'doesFamilyShootings'
},
{
label: 'Expérience Grossesse',
key: 'doesPregnancyShootings'
},
{
label: 'Expérience Crèche/Ecole,',
key: 'doesNurseryAndSchoolShootings'
},
{
label: 'Années d'expérience',
key: 'experienceYears'
},
{
label: 'Site internet',
key: 'website'
},
{
label: 'Compte Instagram',
key: 'instagram'
},
{
label: 'Page facebook',
key: 'facebook'
},
{
label: 'Présentez-vous',
key: 'selfPresentation'
},
{
label: 'Commentaires',
key: 'additionalComment'
},
{
label: 'Commentaires LSDP',
key: 'backOfficePrivateNotes'
},
{
label: 'Reflex numérique',
key: 'hasDigitalReflex'
},
{
label: 'Flash cobra ou équivalent',
key: 'hasCobraFlash'
},
{
label: 'Kit studio photo portable',
key: 'hasStudioKit'
},
{
label: 'Accessoires photos pour séance grossesse',
key: 'hasPregnancyAccessories'
},
{
label: 'Accessoires photos pour séance naissance',
key: 'hasBirthAccessories'
},
{
label: 'Boitier',
key: 'cameras'
},
{
label: 'Objectif',
key: 'lens'
},
{
label: 'Shootings au domicile clients',
key: 'canShootAtHome'
},
{
label: 'Shootings en extérieur',
key: 'canShootOutside'
},
{
label: 'Shootings dans votre propre studio',
key: 'canShootInStudio'
},
{
label: 'Disponibilités temps de travail',
key: 'availableTime'
},
{
label: 'A pied',
key: 'isMovingByFoot'
},
{
label: 'A vélo',
key: 'isMovingByBicycle'
},
{
label: 'Voiture scooter',
key: 'isMovingByPersonalVehicle'
},
{
label: 'Transports public',
key: 'isMovingByPublicTransportation'
},
{
label: 'Rayon d'action',
key: 'actionZone'
},
{
label: 'Zones géographique auxiliaires',
key: 'auxiliaryActionZones'
},
{
label: 'Voiture scooter',
key: 'isMovingByPersonalVehicle'
},
{
label: 'Voiture scooter',
key: 'isMovingByPersonalVehicle'
},
{
label: 'Voiture scooter',
key: 'isMovingByPersonalVehicle'
},
{
label: 'Date de création',
key: 'creationDate'
},
{
label: 'Date de dernière mise à jour',
key: 'lastModificationDate'
},
{
label: 'Date de validation du dossier complet',
key: 'applicationValidationDate'
},
{
label: 'Date d'activation du dossier',
key: 'memberAcceptanceDate'
},
]

"Identifiant,Statut,Date de début d'innactivité,Date de fin d'innactivité,Prénom,Nom,Date de naissance,Mobile,Email,Mot de passe,Confirmation de mot de passe,Adresse ligne 1,Adresse ligne 2,Adresse Code postal,Adresse Ville,Localisation,Type structure,Nom entreprise,Entreprise ligne 1,Entreprise ligne 2,Entreprise Code postal,Entreprise Ville,Entreprise Localisation,Siren,Code établissement,Soumis à la TVA,Taux TVA,Code TVA Intracommunautaire,BIC,IBAN,Contrat,Annexes contrat,Police d'assurance,Mandat d'autofacturation,Entreprise Localisation,Expérience Naissance,Expérience BB/Enfant,Expérience Famille,Expérience Grossesse,Expérience Crèche/Ecole,,Années d'expérience,Site internet,Compte Instagram,Page facebook,Présentez-vous,Commentaires,Commentaires LSDP,Reflex numérique,Flash cobra ou équivalent,Kit studio photo portable,Accessoires photos pour séance grossesse,Accessoires photos pour séance naissance,Boitier,Objectif,Shootings au domicile clients,Shootings en extérieur,Shootings dans votre propre studio,Disponibilités temps de travail,A pied,A vélo,Voiture scooter,Transports public,Rayon d'action,Zones géographique auxiliaires,Voiture scooter,Voiture scooter,Voiture scooter,Date de création,Date de dernière mise à jour,Date de validation du dossier complet,Date d'activation du dossierrn,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,rn,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,rn,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,"

用于将CSV转换为JSON:

let csvData ="First Name,Last Name,Phone NumberrnJohn,Doe,0102030405rnJoe,Dohn,0102030406";
let headers = [
{
label: "First Name",
key: "firstName"
},
{
label: "Last Name",
key: "lastName"
},
{
label: "Phone Number",
key: "phone"
}
];
const convertCsvToJson = (csvData, headers) => {
let tempCsvData = csvData.split("rn");
let csvToJson = [];
if (tempCsvData && tempCsvData.length > 0) {
let inputHeaders = tempCsvData[0].split(",");
//To find out the required headers on which position.
for (let i = 0; i < headers.length; i++) {
const header = headers[i];
let index = inputHeaders.indexOf(header.label);
if (index > -1) {
header.index = index;
} else {
//Since It is not present in CSV
headers.splice(i, 1);
}
}
for (let i = 1; i < tempCsvData.length; i++) {
const temp = tempCsvData[i].split(",");
let jsonData = {};
for (let j = 0; j < headers.length; j++) {
const header = headers[j];
if (temp[header.index]) {
jsonData[header.key] = temp[header.index];
}
}
csvToJson.push(jsonData);
}
}
return csvToJson;
};
console.log(convertCsvToJson(csvData, headers));

用于将JSON转换为CSV:

let jsonData = [
{
firstName: "John",
lastName: "Doe",
phone: "0102030405"
},
{
firstName: "Joe",
lastName: "Dohn",
phone: "0102030406"
}
];
let headers = [
{
label: "First Name",
key: "firstName"
},
{
label: "Last Name",
key: "lastName"
},
{
label: "Phone Number",
key: "phone"
}
];
const convertJsonToCsv = (jsonData, headers) => {
// To avoid any errors
let jsonToCsv = "";
if (jsonData && jsonData.length > 0 && headers && headers.length > 0) {
// Adding columns names to the csv as it should be the starting point
for (let i = 0; i < headers.length; i++) {
const header = headers[i];
jsonToCsv += header.label || "";
if (i < headers.length-1) {
jsonToCsv += ",";
}
}
jsonToCsv+='rn'
for (let i = 0; i < jsonData.length; i++) {
const temp = jsonData[i];
for (let j = 0; j < headers.length; j++) {
const header = headers[j];
jsonToCsv += temp[header.key] || "";
if (j < headers.length-1) {
// If we dont keep this condition it will add ',' to the last column also which we dont need.
jsonToCsv += ",";
}
}
if (i < jsonData.length-1) {
jsonToCsv += "rn";
}
}
}
return jsonToCsv;
};
console.log(convertJsonToCsv(jsonData, headers));

相关内容

  • 没有找到相关文章