gpt4 book ai didi

python - 在Python中将JSON转换为CSV : List indices must be integers,而不是str

转载 作者:行者123 更新时间:2023-11-30 23:13:03 25 4
gpt4 key购买 nike

我正在尝试使用 Python 将 JSON 文件转换为 CSV,但在出现一些错误消息(以及后续修复...我认为)之后,我现在收到以下错误:

TypeError: List indices must be integers, not str

我查看了类似的线程,似乎这个错误很容易修复,但是使用其他线程上的建议,我仍然无法让它工作。

我正在尝试的代码如下所示(只有数百行,我只是稍微清理了一下下面的示例)

import csv
import json

x= r"""[
[{"post_header": ["username - 09 Apr 2015 - 19:58:55 - 1 of 6"], "post": ["example message", "\n", "\nexample message"], "post_thread_url": ["http://www.examplewebsite.com/message1"], "post_symbol": ["EG"], "post_title": ["Example Title"]}]
]"""

x = json.loads(x.replace('\n', ''))

f = csv.writer(open("filename.csv", "wb+"))

f.writerow(["post_header", "post", "post_thread_url", "post_symbol", "post_title"])

for x in x:
f.writerow([x["post_header"],
x["post"],
x["post_thread_url"],
x["post_symbol"],
x["post_title"]])

最佳答案

我们的输入是列表-->列表-->字典

意味着我们必须迭代主列表并从项目中选择第一个值。

data = r"""[
[
{"post_header": ["username - 09 Apr 2015 - 19:58:55 - 1 of 6"], "post": ["example message", "\n", "\nexample message"], "post_thread_url": ["http://www.examplewebsite.com/message1"], "post_symbol": ["EG"], "post_title": ["Example Title"]}
]
]"""

正确使用变量名称,不要创建同名变量。

演示:

import csv
import json

data = r"""[
[
{"post_header": ["username - 09 Apr 2015 - 19:58:55 - 1 of 6"], "post": ["example message", "\n", "\nexample message"], "post_thread_url": ["http://www.examplewebsite.com/message1"], "post_symbol": ["EG"], "post_title": ["Example Title"]}
]
]"""

data_list = json.loads(data.replace('\n', ''))

#- Open file by "with" statement (so no need to close file i.e. fp.close() )
with open("filename.csv", "wb+") as fp:
# Create CSV file object.
root = csv.writer(fp)
#- Write first row in CSV file.
root.writerow(["post_header", "post", "post_thread_url", "post_symbol", "post_title"])
#- Iterate every item from the Data list:
for i in data_list:
# As Item i is again list, so pick first element from the list which is type dictionary.
# i >>>is list
# i[0] >>> is dictionary
# i[0]["post_header"] >> get value of post_header
root.writerow([i[0]["post_header"],
i[0]["post"],
i[0]["post_thread_url"],
i[0]["post_symbol"],
i[0]["post_title"]])

关于python - 在Python中将JSON转换为CSV : List indices must be integers,而不是str,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29540366/

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