Search code examples
pythonjsoncsvraspberry-pi3

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?


Solution

  • 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)