我正在尝试将JSON文件转换为CSV文件,但是当我运行构建时,它仅返回2行标题和第一个条目。
不确定发生了什么事,我尝试了几种不同的变体,但似乎没有任何效果,不确定是因为文件太大还是不超过6百万行...
import json
import csv
with open('result.json') as jsonfile:
data=jsonfile.read()
#ParseFile
jsonobj = json.loads(data)
keylist = []
for key in jsonobj[0]:
keylist.append(key)
f = csv.writer(open("test-kyle.csv", "w"))
f.writerow(keylist)
for record in jsonobj:
currentrecord = []
for key in keylist:
currentrecord.append(record[key])
f.writerow(currentrecord)
这是示例JSON文件:
[
{
"text": "<@U48TMD5QS> has joined the channel",
"ts": "1491388552.433852"
},
{
"text": "*Channel: failed_signup* \nPhone number 123218736 failed to sign up on UGANDA",
"ts": "1491477391.593892"
},
{
"text": "*Channel: failed_signup* \nPhone number 723880908 failed to sign up on UGANDA",
"ts": "1491477392.594092"
},
{
"text": "*Channel: failed_signup* \nPhone number 723880908 failed to sign up on UGANDA",
"ts": "1491477393.594269"
},
{
"text": "*Channel: failed_signup* \nPhone number 723880666 failed to sign up on UGANDA",
"ts": "1491477393.594395"
},
{
"text": "*Channel: IT_ALERTS_GMAIL* \n[kve-t460] Failed to complete import cycle",
"ts": "1491477394.594630"
},
{
"text": "*Channel: failed_signup* \nPhone number abcdefg failed to sign up on UGANDA",
"ts": "1491477434.604899"
},
{
"text": "<@U1Y9UJD8V> has joined the channel",
"ts": "1493358499.130025"
}
]
答案 0 :(得分:0)
您的缩进被弄乱了很多。请小心,否则您的代码会起作用:
import json
import csv
with open('result.json') as jsonfile:
data=jsonfile.read()
#ParseFile
jsonobj = json.loads(data)
keylist = []
for key in jsonobj[0]:
keylist.append(key)
f = csv.writer(open("test-kyle.csv", "w"))
f.writerow(keylist)
for record in jsonobj:
currentrecord = []
for key in keylist:
currentrecord.append(record[key])
f.writerow(currentrecord)
答案 1 :(得分:0)
您需要更正for循环
for key in jsonobj:
keylist.append(key)
答案 2 :(得分:-1)
检查代码上两个for循环的缩进!
答案 3 :(得分:-2)
Python需要4个空格用于缩进。如果您的代码未缩进,则您的keyList为空,它将跳过循环
for key in jsonobj[0]:
keylist.append(key)