简体   繁体   English

将CSV转换为JSON时未在python中获得预期的输出

[英]Not getting expected output in python when converting a csv to json

I have an excel file in which data is saved in csv format in such a way.This data is present in the excel file as shown below,under column A (The CSV File is generated by LabView Software code which i have written to generate data).I have also attached an image of the csv file for reference at the end of my question. 我有一个excel文件,数据以这种方式以csv格式保存。该数据显示在excel文件中,如下所示,在A列下(CSV文件由LabView Software代码生成,我已编写该代码来生成数据)。我在问题的末尾还附上了csv文件的图像以供参考。

RPM,Load Current,Battery Output,Power Capacity
1200,30,12,37
1600,88,18,55

I want to create a Json file in such format 我想以这种格式创建一个Json文件

{  
   "power_capacity_data" :
   {
   "rpm" : ["1200","1600"],
   "load_curr" : ["30","88"],
   "batt_output" : ["12","18"],
   "power_cap" : ["37","55"]
   }
 }

This is my code 这是我的代码

import csv
import json 

def main():

    #created a dictionary so that i can append data to it afterwards

    power_data = {"rpm":[],"load_curr":[],"batt_output":[],"power_cap":[]}

    with open('power1.lvm') as f:
        reader = csv.reader(f)

        #trying to append the data of column "RPM" to dictionary
       rowcount = 0
       for row in reader:   
           if rowcount == 0:
               #trying to skip the first row
               rowcount = rowcount + 1 
           else:
               power_data['rpm'].append(row[0])
               print(row)

        json_report = {}        
        json_report['pwr_capacity_data'] = power_data
        with open('LVMJSON', "w") as f1:
            f1.write(json.dumps(json_report, sort_keys=False, indent=4, separators=(',', ': '),encoding="utf-8",ensure_ascii=False))
            f1.close()


 if __name__ == "__main__":
     main()

The output json file that i am getting is this:(please ignore the print(row) statement in my code) 我得到的输出json文件是这样的:(请忽略我代码中的print(row)语句)

{
"pwr_capacity_data": 
  {
    "load_curr": [],
    "rpm": [
        "1200,30,12.62,37.88",
        "1600,88,18.62,55.88"
    ],
    "batt_output": [],
    "power_cap": []
  } 
}

The whole row is getting saved in the list,but I just want the values under the column RPM to be saved .Can someone help me out with what I may be doing wrong.Thanks in advance. 整个行都将保存在列表中,但我只想保存RPM列下的值。有人可以帮我解决我可能做错的事情。谢谢。 I have attached an image of csv file to just in case it helps 我附上一张csv文件的图片以防万一

You could use Python's defaultdict to make it a bit easier. 您可以使用Python的defaultdict使其变得更容易。 Also a dictionary to map all your header values. 也是映射所有标头值的字典。

from collections import defaultdict    
import csv
import json

power_data = defaultdict(list)

header_mappings = {
    'RPM' : 'rpm',
    'Load Current' : 'load_curr',
    'Battery Output' : 'batt_output',
    'Power Capacity' : 'power_cap'}

with open('power1.lvm', newline='') as f_input:
    csv_input = csv.DictReader(f_input)

    for row in csv_input:
        for key, value in row.items():
            power_data[header_mappings[key]].append(value)

with open('LVMJSON.json', 'w') as f_output:            
    json.dump({'power_capacity_data' : power_data}, f_output, indent=2)

Giving you an output JSON file looking like: 给您一个输出JSON文件,如下所示:

{
  "power_capacity_data": {
    "batt_output": [
      "12",
      "18"
    ],
    "power_cap": [
      "37",
      "55"
    ],
    "load_curr": [
      "30",
      "88"
    ],
    "rpm": [
      "1200",
      "1600"
    ]
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM