【问题标题】:Converting JSON to CSV and CSV to JSON with custom headers Javascript使用自定义标头 Javascript 将 JSON 转换为 CSV 和 CSV 到 JSON
【发布时间】:2021-01-14 22:39:18
【问题描述】:

我正在努力寻找一种无需外部库即可实现支持 csv 格式的导入/导出功能的好方法。任何可以帮助我的人都将成为救命稻草。真的!

我有一个 csv 字符串,我将其称为“A”:

"First Name,Last Name,Phone Number\r\nJohn,Doe,0102030405\r\nJoe,Dohn,0102030406"

我有一个 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,它实际上是 mongoose 集合的一个元素:

[
    {
        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 dossier\r\n,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,\r\n,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,\r\n,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,"

【问题讨论】:

    标签: javascript node.js json csv parsing


    【解决方案1】:

    用于将 CSV 转换为 JSON:

    let csvData ="First Name,Last Name,Phone Number\r\nJohn,Doe,0102030405\r\nJoe,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("\r\n");
      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+='\r\n'
        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 += "\r\n";
          }
        }
      }
      return jsonToCsv;
    };
    
    console.log(convertJsonToCsv(jsonData, headers));
    
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-23
      • 2021-07-24
      • 1970-01-01
      • 2013-03-01
      • 2019-08-21
      • 2014-12-24
      • 1970-01-01
      相关资源
      最近更新 更多