如何用Python将CSV转换为JSON(附实例)

2,675 阅读4分钟

将CSV文件转换为JSON文件的5个简单步骤

你可以通过以下五个步骤将CSV文件转换为JSON文件。

  1. 导入csvjson
  2. 在阅读模式下使用 [open(path_to_csv, 'r')](https://blog.finxter.com/python-open-function/)函数在上下文管理器(=with 环境)中打开CSV作为文件对象。
  3. 使用csv.DictReader(fobj) 将CSV内容加载到Python中,并传递刚刚创建的文件对象。
  4. 遍历每个row ,并使用其中一列值作为键更新新创建的字典 my_jsonmy_json[key] = row
  5. 使用函数将my_json 字典数据存储在一个JSON文件中。 [json.dumps(my_json)](https://blog.finxter.com/how-to-serialize-a-python-dict-into-a-string-and-back/)函数存储在一个JSON文件中。

下面是一个将CSV文件'my_file.csv' 转换为JSON文件'my_file.json' 的代码例子。

import csv
import json 


csv_file = 'my_file.csv'
json_file = 'my_file.json'

my_json = {}
with open(csv_file, 'r') as fobj:
    reader = csv.DictReader(fobj)
    for row in reader:
        # Use one of the CSV column names as a key
        key = row['Name']
        my_json[key] = row 

with open(json_file,'w') as fobj:
    fobj.write(json.dumps(my_json, indent=2))

注意,你应该使用CSV中的一个列作为键。在这个例子中,我们使用了CSV文件中的列'Name'。在你的情况下,你将需要使用你自己的列头。

输入CSV文件。

Name,Job,Age,Income
Alice,Programmer,23,110000
Bob,Executive,34,90000
Carl,Sales,45,50000

输出JSON文件。

{
  "Alice": {
    "Name": "Alice",
    "Job": "Programmer",
    "Age": "23",
    "Income": "110000"
  },
  "Bob": {
    "Name": "Bob",
    "Job": "Executive",
    "Age": "34",
    "Income": "90000"
  },
  "Carl": {
    "Name": "Carl",
    "Job": "Sales",
    "Age": "45",
    "Income": "50000"
  }
}

你可以在我们的交互式Jupyter笔记本中自己尝试,这里。

Python Convert CSV to JSON

Python将CSV文件转换为带有列头的JSON文件

之前介绍的csv.DictReader() 方法假定CSV中的第一行是标题。因此,第一行被用作CSV的页眉--例如,使用row['Name'] ,访问列'Name' 的特定行键。

Python将CSV转换为JSON,不含页眉

之前介绍的csv.DictReader() 方法假定CSV中的第一行是头。

如果你的CSV文件在第一行没有任何头信息,你可以用 **fieldnames**``csv.DictReader() 方法的参数,该方法接收一连串的列标(字符串)。

下面是DictReader() 方法的语法。

class csv.DictReader(f, fieldnames=None, restkey=None, restval=None, 
dialect='excel', *args, **kwds)

"fieldnames "参数是一个序列。如果省略了fieldnames ,文件f 的第一行的值将被用作fieldnames" -文档

下面的代码片断显示了如何通过设置自定义列(标题)字符串作为列表 ['XXX', 'YYY', 'ZZZ', '---'] ,将相同的没有标题的CSV转换为JSON文件。

import csv
import json 


csv_file = 'my_file.csv'
json_file = 'my_file.json'

my_json = {}
with open(csv_file, 'r') as fobj:
    reader = csv.DictReader(fobj, fieldnames=['XXX', 'YYY', 'ZZZ', '---'])
    for row in reader:
        key = row['---']
        my_json[key] = row 

with open(json_file,'w') as fobj:
    fobj.write(json.dumps(my_json, indent=2))

下面是输入和输出的文件。

输入CSV文件。

Name,Job,Age,Income
Alice,Programmer,23,110000
Bob,Executive,34,90000
Carl,Sales,45,50000

输出JSON文件。

{
  "Income": {
    "XXX": "Name",
    "YYY": "Job",
    "ZZZ": "Age",
    "---": "Income"
  },
  "110000": {
    "XXX": "Alice",
    "YYY": "Programmer",
    "ZZZ": "23",
    "---": "110000"
  },
  "90000": {
    "XXX": "Bob",
    "YYY": "Executive",
    "ZZZ": "34",
    "---": "90000"
  },
  "50000": {
    "XXX": "Carl",
    "YYY": "Sales",
    "ZZZ": "45",
    "---": "50000"
  }
}

或者,作为一个屏幕截图。

你可以看到,现在第一行被用作正常的CSV输入行,而不是像前面的例子那样,在没有指定DictReader() 方法的fieldnames 参数的情况下被用作标题。

Python将CSV转换为JSON Pandas

[pandas.to_json()](https://blog.finxter.com/pandas-dataframe-to_json-method/)方法将一个DataFrame对象转换为JSON字符串。

这个方法的语法如下。

# Syntax to_json()
DataFrame.to_json(path_or_buf=None, orient=None, date_format=None,
double_precision=10, force_ascii=True, date_unit='ms', 
default_handler=None, lines=False, compression='infer', index=True, 
indent=None, storage_options=None)

下面的例子将countries.csv 文件读入一个DataFrame。然后这个DataFrame转换为JSON。

df = pd.read_csv('countries.csv').head()
result = df.to_json(indent=4, orient='records', lines=True)
print(result)
  • 第[1]行读入countries.csv 文件的前五(5)行(头部)。输出保存到一个DataFrame (df)。
  • 第[2]行做了以下工作。
    • 将DataFrame转换为JSON格式
    • 通过将每条记录从左边缩进四(4)个空格来格式化输出
    • 将方向参数设置为记录,将行设置为True (见上述定义)。
    • 将输出保存到result
  • 第[3]行将结果输出到终端。

输出 -result

{
"Country":"Germany",
"Capital":"Berlin",
"Population":83783942,
"Area":357021
}
{
"Country":"France",
"Capital":"Paris",
"Population":67081000,
"Area":551695
}
{
"Country":"Spain",
"Capital":"Madrid",
"Population":47431256,
"Area":498511
}
{
"Country":"Italy",
"Capital":"Rome",
"Population":60317116,
"Area":301338
}
{
"Country":"Poland",
"Capital":"Warsaw",
"Population":38383000,
"Area":312685
}

Pheww!让我们以更有趣的方式来结束这篇文章吧!!(s.w.org/images/core…)

程序员的幽默

Q: How do you tell an introverted computer scientist from an 
extroverted computer scientist?

A: An extroverted computer scientist looks at your shoes when he talks to you.