【问题标题】:Converting a CSV file to JSON in python在 python 中将 CSV 文件转换为 JSON
【发布时间】:2015-01-13 23:52:55
【问题描述】:

所以我试图在 csvfile 中加载数据,将其转换为字典列表,然后将结果作为 JSON 保存到 jsonfile。这就是我现在所拥有的。当我尝试打开并加载 json 文件时,我得到一个“ValueError:没有 JSON 对象可以被解码”,我会很感激任何提示!

def csv_to_json(csvfile, jsonfile):
    reader = csv.DictReader(csvfile.splitlines(), delimiter=' ', skipinitialspace=True,
                        fieldnames=['dept', 'code', 'section',
                                    'name', 'instructor', 'type','location])
    writer = csv.DictWriter(open(jsonfile,'wb'), fieldnames=reader.fieldnames)

【问题讨论】:

    标签: python json


    【解决方案1】:

    我结束了这个,写任意 CSV:

    import json
    import csv
    
    def csv_to_json(csvfile, jsonfile):
        """
        Read a CSV file and output it as JSON. Assumes the csv has a header row.
        """
        with open(csvfile, 'rU') as f:
            reader = csv.DictReader(f)
            data_dict = []
            for row in reader:
                data_dict.append(row)
            print(len(data_dict))
            with open(jsonfile, 'w') as g:
                json.dump(data_dict, g)
    

    【讨论】:

      【解决方案2】:

      试试这个:

      import json
      import csv
      
      
      def csv_to_json(csvfile, jsonfile):
          ''''''
          with open(csvfile, 'rb') as f:
             reader = csv.DictReader(f, delimiter=',', fieldnames=['head1', 'head2']) 
             open(jsonfile, 'w').write(json.dumps(list(reader)) # if your csv file is not very large                  
      

      【讨论】:

        【解决方案3】:

        记住 JSON 与 python 对象/字典不同,看看这个answer
        因此,您必须使用json.dumps 对其进行编码,然后使用json.loads 将其解码回有效的python dict

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2023-03-03
          • 1970-01-01
          • 2017-11-30
          • 2018-03-06
          • 2019-08-15
          • 1970-01-01
          • 2018-07-14
          相关资源
          最近更新 更多