如何将 JSON 转换为 CSV? [英] How can I convert JSON to CSV?
问题描述
我有一个 JSON 文件,我想将其转换为 CSV 文件.我怎样才能用 Python 做到这一点?
I have a JSON file I want to convert to a CSV file. How can I do this with Python?
我试过了:
import json
import csv
f = open('data.json')
data = json.load(f)
f.close()
f = open('data.csv')
csv_file = csv.writer(f)
for item in data:
csv_file.writerow(item)
f.close()
然而,它没有用.我正在使用 Django,我收到的错误是:
However, it did not work. I am using Django and the error I received is:
`file' object has no attribute 'writerow'`
然后我尝试了以下操作:
I then tried the following:
import json
import csv
f = open('data.json')
data = json.load(f)
f.close()
f = open('data.csv')
csv_file = csv.writer(f)
for item in data:
f.writerow(item) # ← changed
f.close()
然后我得到错误:
`sequence expected`
示例 json 文件:
Sample json file:
[{
"pk": 22,
"model": "auth.permission",
"fields": {
"codename": "add_logentry",
"name": "Can add log entry",
"content_type": 8
}
}, {
"pk": 23,
"model": "auth.permission",
"fields": {
"codename": "change_logentry",
"name": "Can change log entry",
"content_type": 8
}
}, {
"pk": 24,
"model": "auth.permission",
"fields": {
"codename": "delete_logentry",
"name": "Can delete log entry",
"content_type": 8
}
}, {
"pk": 4,
"model": "auth.permission",
"fields": {
"codename": "add_group",
"name": "Can add group",
"content_type": 2
}
}, {
"pk": 10,
"model": "auth.permission",
"fields": {
"codename": "add_message",
"name": "Can add message",
"content_type": 4
}
}
]
推荐答案
With the pandas
库,这就像使用两个命令一样简单!
With the pandas
library, this is as easy as using two commands!
df = pd.read_json()
read_json 转换 JSON字符串到熊猫对象(系列或数据框).然后:
read_json converts a JSON string to a pandas object (either a series or dataframe). Then:
df.to_csv()
可以返回字符串或直接写入 csv 文件.请参阅 to_csv 的文档.
Which can either return a string or write directly to a csv-file. See the docs for to_csv.
基于之前答案的冗长,我们都应该感谢熊猫的捷径.
Based on the verbosity of previous answers, we should all thank pandas for the shortcut.
对于非结构化 JSON,请参阅此答案.
For unstructured JSON see this answer.
这篇关于如何将 JSON 转换为 CSV?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!