JSON Key和python中csv文件的值

时间:2017-03-05 06:56:34

标签: python json opencsv

这是我的file_t.JSON从请求内容写到csv / json文件

{"w1":"R"}
{"w2":"R2"}
{"w3":"R3"}
{"w4":"R4"}
{"w5":"R5"}

我期待下面的代码应该给我以下结果Expecting output.csv

w1 r
w2 R2
w3 R3
W4 R4
w5 R5

这是我的代码

import csv

f1 = file ("output.csv","w")

f2 = file ("file_t.JSON","rU")

with open("file_t.JSON") as f:
    csvr = csv.reader(f, delimiter=' ')
    csvr.next()
    for rec in csvr:
        key, values_txt = rec
        values = values_txt.split(',')
        print key, values
        f1.write(values)

不打印,写入输出文件。

1 个答案:

答案 0 :(得分:2)

逐行读取JSON文件,并使用json.loads()将每行转换为Python字典。然后将其写入CSV文件:

import csv
import json

with open("file_t.JSON") as infile, open('output.csv', 'w') as outfile:
    writer = csv.writer(outfile, delimiter=' ')
    for line in infile:
        d = json.loads(line)
        writer.writerows(d.items())