我正在尝试使用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"]])

最佳答案

我们的输入是list-> list-> dictionary

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

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"]])

10-08 11:41