【发布时间】:2018-05-17 13:30:37
【问题描述】:
我正在尝试从来自 PushShift API 但遇到 TypeError 的 JSON 数据写入 CSV 文件。我的代码如下
import requests
import csv
import json
from urllib.request import urlopen
url = 'https://api.pushshift.io/reddit/comment/search/?subreddit=science&filter=parent_id,id,author,created_utc,subreddit,body,score,permalink'
page = requests.get(url)
page_json = json.loads(page.text)
print(page.text)
f = csv.writer(open("test.csv",'w+', newline=''))
f.writerow(["id", "parent_id", "author", "created_utc","subreddit", "body", "score"])
for x in page_json:
f.writerow([x["data"]["id"],
x["data"]["parent_id"],
x["data"]["author"],
x["data"]["created_utc"],
x["data"]["subreddit"],
x["data"]["body"],
x["data"]["score"]])
我得到的错误是:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-3-82784a93576b> in <module>()
11 f.writerow(["id", "parent_id", "author", "created_utc","subreddit", "body", "score"])
12 for x in page:
---> 13 f.writerow([x["data"]["id"],
14 x["data"]["parent_id"],
15 x["data"]["author"],
TypeError: byte indices must be integers or slices, not str
我在这里尝试了解决方案:How can I convert JSON to CSV?
这可能是也可能不是我遇到的实际问题。任何建议将不胜感激!
【问题讨论】:
-
看来
x或x["data"]不是字典而是字符串。尝试打印出你的值进行调试,看看x的实际结构是什么 -
你应该使用
page_json,而不是page -
您正在迭代
page而不是page_json。 -
for x in page_json:.... -
抱歉,页面有错别字。当我运行正确的代码时,它给出了这个错误 TypeError: string indices must be integers