python 将csv 转 json

python处理csv转换为json

下面是我爬取的拉钩网数据转化成json,然后传递给前端绘制可视化接口。因为我采用了scrapy爬取数据以csv的文件形式存储,这样便于使用pandas进行数据清理,而为了将最终清理的数据编程前端可读的数据,将csv转化成json。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# csv转json
csv_file = 'lagou_new.csv'
json_file = 'lagou_json.json'

with open(csv_file,'r',encoding='utf-8') as csv_f:
with open(json_file,'w',encoding='utf-8') as json_f:
# 设定键名
filednames=('index','city','education','industry','job_keyword','publish_time','salary','scale','technology_keyword','treatment')
# 以字典形式读取csv文件内容,每一个字典中的键名对应filednames
# 有两个参数,第一个为文件描述符,第二个为字典对应的键名
reader = csv.DictReader(csv_f,filednames)
# 将字典序列化为json字符串,DictReader返回的可迭代的对象
out = json.dumps([i for i in reader],ensure_ascii=False) # 不让中文显示成ascii
# 将序列化后的文件写入文件中
json_f.write(out)

说明:最后两句也可以写成json.dump([i for i in reader],json_f,ensure_ascii=False)


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!