我有csv fromat中的代码输出,我试图将其转换为json,但它在json文件中转换为一些错误。这是csv代码。如果你告诉我如何使用正确的输出json格式将输出转换为json而不是csv,我将感激不尽。
谢谢
print >> out, 'text '
rows = zip(texts)
from csv import writer
csv = writer(out)
for row in rows:
values = [(value.encode('utf8') if hasattr(value, 'encode') else value) for value in row]
csv.writerow(values)
out.close()
答案 0 :(得分:0)
Json应该已经定义了数据结构。我使用以下结构作为示例:
[{"title" : "Gone with the wind", "description" : "A book"},
{"title" : "White Fang", "description" : "A book"},
{"title" : "Dracula", "description" : "A book"},
{"title" : "Van Helsing", "description" : "A movie"},
...]
以下是将其转换为json数组对象并写入文件的代码:
# I'm not sure what you are doing here, but zip returns a list of tuples
# For example: [("Gone with the wind", "A book"), ("Van Helsing", "A movie")...]
rows = zip(texts)
with open(filename, 'w') as f:
data = list()
for title, desc in rows: # According to your tuple
data.append(dict(title=title, description=desc))
json.dump(data, f) # Write the list into the output file