【问题标题】:Convert CSV with nested headers to JSON将带有嵌套标题的 CSV 转换为 JSON
【发布时间】:2020-12-29 19:45:13
【问题描述】:

到目前为止,我有这段代码(在教程的帮助下):

import csv, json

csvFilePath = "convertcsv.csv"
jsonFilePath = "newResult.json"

# Read the CSV and add the data to a dictionary...
data = {}

with open(csvFilePath) as csvFile:
    csvReader = csv.DictReader(csvFile)
    for csvRow in csvReader:
        data = csvRow

# Write data to a JSON file...
with open(jsonFilePath, "w") as jsonFile:
    jsonFile.write(json.dumps(data, indent=4))

我想要的输出是这样的:

{
  "userID": "string", 
  "username": "string", 
  "age": "string",
  "location": {
    "streetName": "string", 
    "streetNo": "string", 
    "city": "string"
  }
}

我不知道如何表示“位置”。

我的实际结果是这样的:

{
    "userID": "string", 
    "username": "string", 
    "age": "string",
    "location/streetName": "string", 
    "location/streetNo": "string", 
    "location/city": "string", 
}

如何将 streetName、streetNo 和 city 分开并放入“位置”?

【问题讨论】:

    标签: python json csv parsing


    【解决方案1】:

    下面是一个简单的脚本应该做你想做的事。结果将是一个以“userID”为键的 json 对象。请注意,为了测试更深层次的嵌套,我使用了一个标题略有不同的 csv 文件 - 但它与您的原始示例一样好。

    import csv, json
    
    infile = 'convertcsv.csv'
    outfile = 'newResult.json'
    
    data = {}
    
    def process(header, value, record):
        key, other = header.partition('/')[::2]
        if other:
            process(other, value, record.setdefault(key, {}))
        else:
            record[key] = value
    
    with open(infile) as stream:
        reader = csv.DictReader(stream)
        for row in reader:
            data[row['userID']] = record = {}
            for header, value in row.items():
                process(header, value, record)
    
    with open(outfile, "w") as stream:
        json.dump(data, stream, indent=4)
    

    输入

    userID,username,age,location/street/name,location/street/number,location/city
    0,AAA,20,This Street,5,This City
    1,BBB,42,That Street,5,That City
    2,CCC,34,Other Street,5,Other City
    

    输出

    {
        "0": {
            "userID": "0",
            "username": "AAA",
            "age": "20",
            "location": {
                "street": {
                    "name": "This Street",
                    "number": "5"
                },
                "city": "This City"
            }
        },
        "1": {
            "userID": "1",
            "username": "BBB",
            "age": "42",
            "location": {
                "street": {
                    "name": "That Street",
                    "number": "5"
                },
                "city": "That City"
            }
        },
        "2": {
            "userID": "2",
            "username": "CCC",
            "age": "34",
            "location": {
                "street": {
                    "name": "Other Street",
                    "number": "5"
                },
                "city": "Other City"
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      我会添加一些自定义逻辑来实现这一点,注意这只是第一级,如果你想要更多,你应该创建一个递归函数:

      # Write data to a JSON file...
      with open(jsonFilePath, "w") as jsonFile:
          for i, v in data.items():
              if '/' in i:
                  parts = i.split('/', 1)
                  data[parts[0]] = {parts[1]: v}
                  data.pop(i)
      
          jsonFile.write(json.dumps(data, indent=4))
      

      【讨论】:

      • 嘿,谢谢!你能解释一下我如何为此创建一个递归函数吗?我想弄清楚但不知道更多......现在它只有“位置/城市”
      【解决方案3】:

      你可以这样使用:

      # https://www.geeksforgeeks.org/convert-csv-to-json-using-python/
      
      import csv 
      import json 
        
        
      # Function to convert a CSV to JSON 
      # Takes the file paths as arguments 
      def make_json(csvFilePath, jsonFilePath): 
            
          # create a dictionary 
          data = {} 
            
          # Open a csv reader called DictReader 
          with open(csvFilePath, encoding='utf-8') as csvf: 
              csvReader = csv.DictReader(csvf) 
                
              # Convert each row into a dictionary  
              # and add it to data 
              for rows in csvReader: 
                    
                  # Assuming a column named 'No' to 
                  # be the primary key 
                  key = rows['No'] 
                  data[key] = rows 
        
          # Open a json writer, and use the json.dumps()  
          # function to dump data 
          with open(jsonFilePath, 'w', encoding='utf-8') as jsonf: 
              jsonf.write(json.dumps(data, indent=4)) 
                
      # Driver Code 
        
      # Decide the two file paths according to your  
      # computer system 
      csvFilePath = r'Names.csv'
      jsonFilePath = r'Names.json'
        
      # Call the make_json function 
      make_json(csvFilePath, jsonFilePath)
      

      欲了解更多信息,请查看https://www.geeksforgeeks.org/convert-csv-to-json-using-python/

      【讨论】:

        猜你喜欢
        • 2019-03-16
        • 1970-01-01
        • 2018-01-07
        • 2020-10-28
        • 2020-04-02
        • 2018-10-27
        • 2021-05-17
        • 2021-01-08
        相关资源
        最近更新 更多