【问题标题】:CSV file to JSON file in PythonCSV文件到Python中的JSON文件
【发布时间】:2012-10-18 09:26:31
【问题描述】:

我在这里和其他地方阅读了很多帖子,但我似乎找不到解决方案。而且我不想在线转换它。

我想用我找到的这段代码hereCSV 文件转换为JSON 文件(没有嵌套,即使我将来可能需要它):

import csv
import json

f = open( 'sample.csv', 'r' )
reader = csv.DictReader( f, fieldnames = ( "id","name","lat","lng" ) )
out = json.dumps( [ row for row in reader ] )
print out

很棒,简单,而且有效。但是我没有得到一个 .csv 文件,而是一个文本输出,如果我复制和粘贴,就是一长行。

我需要一个可读的 .json 文件,最好保存到 .json 文件中。 这可能吗?

【问题讨论】:

    标签: python json csv


    【解决方案1】:

    要获得更具可读性的 JSON,请尝试 dumps() 中的 indent 参数:

    print json.dumps(..., indent=4)
    

    但是 - 为了看起来更像原始 CSV 文件,您可能想要单独编码每一行,然后使用 JSON 数组语法将它们全部连接起来:

    out = "[\n\t" + ",\n\t".join([json.dumps(row) for row in reader]) + "\n]"
    

    这应该会给你类似的东西:

    [
        {"id": 1, "name": "foo", ...},
        {"id": 2, "name": "bar", ...},
        ...
    ]
    

    如果您需要帮助将结果写入文件,请尝试this tutorial

    【讨论】:

    • 感谢成功,现在我需要了解如何在 csv 中构造数据以从中获取嵌套的 json。再次感谢
    【解决方案2】:

    如果您想要更易读的 JSON 文件格式,请像这样使用它:

    json.dump(output_value, open('filename','w'), indent=4, sort_keys=False)
    

    【讨论】:

      【解决方案3】:

      这是一个完整的脚本。此脚本使用第一行的逗号分隔值作为 JSON 输出的键。输出 JSON 文件将使用与输入 CSV 文件名相同的文件名自动创建或覆盖,只是将 .csv 文件扩展名替换为 .json。

      CSV 文件示例:

      id,longitude,latitude
      1,32.774,-124.401
      2,32.748,-124.424
      4,32.800,-124.427
      5,32.771,-124.433
      

      Python 脚本:

      csvfile = open('sample.csv', 'r')
      jsonfile = open('sample.csv'.replace('.csv', '.json'), 'w')
      
      jsonfile.write('{"' + 'sample.csv'.replace('.csv', '') + '": [\n') # Write JSON parent of data list
      fieldnames = csvfile.readline().replace('\n','').split(',')        # Get fieldnames from first line of csv
      num_lines = sum(1 for line in open('sample.csv')) - 1              # Count total lines in csv minus header row
      
      reader = csv.DictReader(csvfile, fieldnames)
      i = 0
      for row in reader:
        i += 1
        json.dump(row, jsonfile)
        if i < num_lines:
          jsonfile.write(',')
        jsonfile.write('\n')
      jsonfile.write(']}')
      

      【讨论】:

        猜你喜欢
        • 2020-07-17
        • 2015-10-10
        • 1970-01-01
        • 1970-01-01
        • 2021-12-21
        • 1970-01-01
        • 1970-01-01
        • 2016-11-10
        • 1970-01-01
        相关资源
        最近更新 更多