【问题标题】:converting CSV to nested Json将 CSV 转换为嵌套的 Json
【发布时间】:2020-10-28 19:36:07
【问题描述】:

请帮帮我!!我还在学习数据结构和 我正在尝试转换此 CSV 文件

key,a,b,c,d,e
key_01,apple,100,200,doll,elephant
key_02,apple,100,200,doll,elephant
key_03,apple,100,200,doll,elephant

转为 Json 格式。我试过这个脚本

   import csv
   import json

    csvFilePath = 'my.csv'
    jsonFilePath = 'my.json'


    def make_json(csvFilePath, jsonFilePath):
        data = {}

with open(csvFilePath, encoding='utf-8') as csvf:
    csvReader = csv.DictReader(csvf)
    for rows in csvReader:
        key = rows["key"]
        data[key] = rows


with open(jsonFilePath, 'w', encoding='utf-8') as jsonf:
    jsonf.write(json.dumps(data, indent=4))

   make_json(csvFilePath, jsonFilePath)

但输出中有关键行

 {
"key_01": {
    "key": "01",
    "a": "apple", 
    "y": "100.0", 
    "c": "cow", 
    "d": "doll", 
    "e": "elephant"
}, 
"key_02": {
  "key":  "02",
    "a": "apple", 
    "y": "100.0", 
    "c": "cow", 
    "d": "doll", 
    "e": "elephant"
}, 
 }

我希望我的最终输出看起来像这样。有什么办法可以做到这一点?请帮帮我。

{
"key_01": {
    "a": "apple", 
    "y": "100.0", 
    "c": "cow", 
    "d": "doll", 
    "e": "elephant"
}, 
"key_02": {
    "a": "apple", 
    "y": "100.0", 
    "c": "cow", 
    "d": "doll", 
    "e": "elephant"
}, 
"key_03": {
    "a": "apple", 
    "y": "100.0", 
    "c": "cow", 
    "d": "doll", 
    "e": "elephant"
}, 

【问题讨论】:

    标签: python json csv dictionary data-structures


    【解决方案1】:

    在这部分代码中:

    for rows in csvReader:
        key = rows["key"]
        data[key] = rows
        del data[key]['key'] # Add this line
    

    【讨论】:

      【解决方案2】:

      使用dict.pop 删除所需的值:

      import csv
      import json
      from io import StringIO
      
      new_str = """key,a,b,c,d,e
      01,apple,100,200,doll,elephant
      02,apple,100,200,doll,elephant
      03,apple,100,200,doll,elephant
      """
      
      data = {}
      csvReader = csv.DictReader(StringIO(new_str))
      for rows in csvReader:
          key = rows.pop("key")
          data[key] = rows
      print(json.dumps(data, indent=4))
      

      输出:

      {
          "01": {
              "a": "apple",
              "b": "100",
              "c": "200",
              "d": "doll",
              "e": "elephant"
          },
          "02": {
              "a": "apple",
              "b": "100",
              "c": "200",
              "d": "doll",
              "e": "elephant"
          },
          "03": {
              "a": "apple",
              "b": "100",
              "c": "200",
              "d": "doll",
              "e": "elephant"
          }
      }
      

      【讨论】:

        【解决方案3】:

        如果您有权访问外部库,则可以使用 pandas 库。它使这项任务非常简单:

        import pandas as pd
        
        # We don't read the key column.
        df = pd.read_csv("my.csv", usecols=["a", "b", "c", "d", "e"])
        
        # We create another column here with your desired format.
        df["indexer"] = [f"record_{i}" for i in df.index]
        # We make it the index, so if you export it to JSON later it will have your desired format.
        df.set_index("indexer", inplace=True)
        
        jsn = df.to_json('my.json', orient="index")
        
        # OR, directly to Python dict for further use
        dct = df.to_dict(orient="index")
        

        【讨论】:

        • 成功了。谢谢你。但我只需要它把“record_01”这样的东西。没有写清楚并使它看起来像索引是我的错。有没有办法做到这一点? ;'(
        猜你喜欢
        • 1970-01-01
        • 2018-01-07
        • 2020-04-02
        • 2018-10-27
        • 2021-05-17
        • 2021-01-08
        • 1970-01-01
        • 2022-01-07
        相关资源
        最近更新 更多