python,从csv格式输出到json
我将代码输出为csv fromat,我试图将其转换为json,但json文件中出现了一些错误。这是csv代码。如果您告诉我如何将输出转换为json,而不是使用正确的输出json格式的csv,我将不胜感激 多谢各位python,从csv格式输出到json,python,json,csv,tweets,Python,Json,Csv,Tweets,我将代码输出为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') i
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()
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
你犯了什么错误