简体   繁体   中英

How to convert columns from CSV file to json such that key and value pair are from different columns of the CSV using python?

I have a CSV file with which contains labels and their translation in different languages:

name                      en_GB     de_DE
-----------------------------------------------
ElementsButtonAbort       Abort     Abbrechen
ElementsButtonConfirm     Confirm   Bestätigen
ElementsButtonDelete      Delete    Löschen
ElementsButtonEdit        Edit      Ãndern

I want to convert this CSV into JSON into following pattern using Python:

{
    "de_De": {
        "translations":{
            "ElementsButtonAbort": "Abbrechen"
                       }
             },
   "en_GB":{
       "translations":{
           "ElementsButtonAbort": "Abort"
                      }
             }
 }

How can I do this using Python?

Say your data is as such:

import pandas as pd

df = pd.DataFrame([["ElementsButtonAbort", "Abort", "Arbrechen"],
                   ["ElementsButtonConfirm", "Confirm", "Bestätigen"],
                   ["ElementsButtonDelete", "Delete", "Löschen"],
                   ["ElementsButtonEdit", "Edit", "Ãndern"]],
                   columns=["name", "en_GB", "de_DE"])

Then, this might not be the best way to do it but at least it works:

df.set_index("name", drop=True, inplace=True)
translations = df.to_dict()

Now, if you want to have get exactly the dictionary that you show as desired output, you can do:

for language in translations.keys():
    _ = translations[language]
    translations[language] = {}
    translations[language]["translations"] = _

Finally, if you wish to save your dictionary into JSON:

import json

with open('PATH/TO/YOUR/DIRECTORY/translations.json', 'w') as fp:
    json.dump(translations, fp)

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