python - 如何使用 python 将列从 CSV 文件转换为 json,以便键和值对来自 CSV 的不同列?

标签 python json csv raspberry-pi3

我有一个 CSV 文件,其中包含标签及其不同语言的翻译:

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

我想使用 Python 将此 CSV 转换为 JSON 为以下模式:

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

如何使用 Python 执行此操作?

最佳答案

假设您的数据是这样的:

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"])

然后,这可能不是最好的方法,但至少它有效:

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

现在,如果您想准确获取显示为所需输出的字典,您可以执行以下操作:

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

最后,如果您希望将字典保存为 JSON:

import json

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

关于python - 如何使用 python 将列从 CSV 文件转换为 json,以便键和值对来自 CSV 的不同列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58693802/

相关文章:

python - 如何每隔一段时间发送文件?

javascript - Angular 2 : unable to return a json mapped from an Http response

javascript - 发送 JSON 对象。如何设置简单的 .net Controller 方法来接收此类型?

python - Pandas 读取错误的列

Python:充满 BOM 的 Youtube HTML

python - 如何在后台运行 Python 子进程管道然后将其终止

python - Monkeypatch 在单元测试 python 中持续存在

python - 如何将数据框转换为csv?

python - 将 csv 导入 dask 中的数据框时命名列

c# - 使用 C# 将大量 CSV 数据插入 mysql 数据库的最快方法是什么?