首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用自定义头Javascript将JSON转换为CSV,将CSV转换为JSON

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

Stack Overflow用户
提问于 2021-01-14 02:12:50
回答 1查看 325关注 0票数 0

在没有外部库的情况下,我很难找到一种实现支持csv格式的导入/导出功能的好方法。任何能帮我的人都是救星。真的!

我有一个csv字符串,我称之为"A":

代码语言:javascript
复制
"First Name,Last Name,Phone Number\r\nJohn,Doe,0102030405\r\nJoe,Dohn,0102030406"

我有一个json数组,我称之为"B":

代码语言:javascript
复制
[
    {
        firstName: "John",
        lastName: "Doe",
        phone: "0102030405"
    },
    {
        firstName: "Joe",
        lastName: "Dohn",
        phone: "0102030406"
    }
]

  • I需要创建一个泛型函数,它使用定义标头的对象数组从A到B
  • ,我还需要创建一个泛型函数,该函数使用定义标头的对象数组从B到A

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

代码语言:javascript
复制
[
    {
        label: "First Name",
        key: "firstName",
    },
    {
        label: "Last Name",
        key: "lastName",
    },
    {
        label: "Phone Number",
        key: "phone",
    }
]

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

代码语言:javascript
复制
[
    {
        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
    },

]

当我试图导出它时,它提供了以下标题:

代码语言:javascript
复制
[
    {
        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,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,"

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-01-14 03:53:33

用于将CSV转换为JSON:

代码语言:javascript
复制
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:

代码语言:javascript
复制
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));
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65712440

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档