gpt4 book ai didi

python - 在 CSV 中嵌入 JSON 的正确格式

转载 作者:太空宇宙 更新时间:2023-11-03 18:12:08 24 4
gpt4 key购买 nike

我正在尝试编写一个 Python 函数来查询返回各种 JSON 片段的 API,并希望将每个片段(一些是对象,更多是 json 数组)放入 .csv 文件中。

转义所有逗号、[、]、"和其他符号以便 Excel 可以在工作表中正确读取的正确方法是什么?

现在,几乎所有内容都会在文件中 JSON 的第一列之后发生变化。将每个 json 对象解析到它们自己的列中并不是我想要做的。

最佳答案

csv 模块将为您处理所有这些事情:

>>> import csv, json
>>> import StringIO
>>> outfile = StringIO.StringIO()
>>> writer = csv.writer(outfile)
>>> writer.writerow([json.dumps({"hello":"world"})]*3)
>>> print outfile.getvalue()
"{""hello"": ""world""}","{""hello"": ""world""}","{""hello"": ""world""}"

>>>

关于python - 在 CSV 中嵌入 JSON 的正确格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25725700/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com