【问题标题】:How to convert CSV to nested JSON in Python如何在 Python 中将 CSV 转换为嵌套的 JSON
【发布时间】:2022-08-21 17:56:31
【问题描述】:

我有以下格式的 csv 文件:

a b c d e
1 2 3 4 5
9 8 7 6 5

我想将此 csv 文件转换为嵌套 JSON 格式,如下所示:

[{\"a\": 1,
\"Purchase\" : {
              \"b\": 2,
              \"c\": 3
              \"d\": 4},
\"Sales\": {
           \"d\": 4,
           \"e\": 5}},
{\"a\": 9,
\"Purchase\" : {
              \"b\": 8,
              \"c\": 7},
\"Sales\": {
           \"d\": 6,
           \"e\": 5}}]

我怎样才能进行这种转变?我似乎无法弄清楚如何在 Python 中进行这种转换。 请记住,这只是示例表,我的真实表具有多列和数千行,因此手动操作并不经济。

直到现在我已经尝试过这段代码:

with open(\"new_data.csv\") as f:
    reader = csv.DictReader(f)
    for r in reader:
        r[\"purchase\"] = {\"b\": r[\'b\'],
                        \"c\": r[\'c\'],
                        }

在这里,我尝试添加所需字典的另一个键值对,但未成功。我也会用Sales 做同样的事情,但这只是示例。

  • 感谢您分享您的问题。您还可以分享到目前为止您尝试过的内容吗?

标签: python json python-3.x csv


【解决方案1】:

一种简单的方法是添加更多列;然后在 pandas 中使用to_json 方法:

import pandas as pd
df = pd.read_csv('your_file.csv')
df['Purchase'] = df[['b','c','d']].to_dict('records')
df['Sales'] = df[['d','e']].to_dict('records')
out = df[['a', 'Purchase', 'Sales']].to_json(orient='records', indent=4)

输出:

[
    {
        "a":1,
        "Purchase":{
            "b":2,
            "c":3,
            "d":4
        },
        "Sales":{
            "d":4,
            "e":5
        }
    },
    {
        "a":9,
        "Purchase":{
            "b":8,
            "c":7,
            "d":6
        },
        "Sales":{
            "d":6,
            "e":5
        }
    }
]

【讨论】:

    【解决方案2】:

    您不需要任何库,只需指定正确的方言,例如对于制表符分隔:

    import csv
    import json
    
    
    with open("tmp4.csv", "r") as f:
        result = [
            {
                "a": row["a"],
                "Purchase": {
                    "b": row["b"],
                    "c": row["c"],
                },
                "Sales": {
                    "d": row["d"],
                    "e": row["e"],
                },
            }
            for row in csv.DictReader(f, dialect='excel-tab')
        ]
    assert (
        json.dumps(result)
        == '[{"a": "1", "Purchase": {"b": "2", "c": "3"}, "Sales": {"d": "4", "e": "5"}}, {"a": "9", "Purchase": {"b": "8", "c": "7"}, "Sales": {"d": "6", "e": "5"}}]'
    )
    

    【讨论】:

      【解决方案3】:

      当您执行r["purchase"] = {"b": ...} 时,您将字典分配回每行对象r,该对象在循环结束时被丢弃。相反,为每条记录创建一个新字典并将其附加到列表中。喜欢:

      result = []
      with open("new_data.csv") as f:
          reader = csv.DictReader(f)
          for r in reader:
              result.append({
                  "a": r["a"],
                  "Purchase" : {
                      "b": r["b"],
                      "c": r["c"],
                      "d": r["d"],
                  },
                  "Sales": {
                      "d": r["d"],
                      "e": r["e"],
                  },
              })
      

      并使用列表理解来创建result

      with open("new_data.csv") as f:
          reader = csv.DictReader(f)
          result = [{
              "a": r["a"],
              "Purchase" : {
                  "b": r["b"],
                  "c": r["c"],
                  "d": r["d"],
              },
              "Sales": {
                  "d": r["d"],
                  "e": r["e"],
              },
          } for r in reader]
      

      【讨论】:

        【解决方案4】:

        从这条线 df['Purchase'] = df[['b','c','d']].to_dict('records') df['Sales'] = df[['d','e']].to_dict('records') out = df[['a', 'Purchase', 'Sales']].to_json(orient='records', indent=4), 我们如何在json中创建一个数组

        目前,此代码生成 json 结构,如 购买:{'b', 'c', 'd'} 销售:{'d', 'e'} 如果我想要像这样的输出 "Purchase":[{"b":1,"c":{"test":"abc"}, "d":{"testing":"def"}}],那么我应该对上面的代码??好心提醒

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-10-27
          • 2021-05-17
          • 2019-07-21
          • 2019-09-24
          • 1970-01-01
          • 1970-01-01
          • 2021-10-21
          相关资源
          最近更新 更多