繁体   English   中英

python,从csv格式输出到json

[英]python , output from csv format to json from

我有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()

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM