Python迭代嵌套的json并保存值

2024-10-01 02:22:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个嵌套的JSON(API)webtie,我想解析它并将其保存到文件中(使用Scrapy framework)。在

我想访问给定元素的每个子元素,这些元素的格式如下

0   {…}
1   {…}
2   {…}
3   {…}
4   {…}
5   {…}
6   {…}
7   {…}
8   {…}
9   {…}
10  {…}

如果我展开元素0,我得到以下值,其中{…}将进一步扩展

^{pr2}$

How does it look like in reality

如何连续访问每个元素,先是0,然后是1,然后是2。。。例如,总计为350,抓取值为

guid   
    rendered "https//:example.com"

并保存到项目。在

我所拥有的:

       results = json.loads(response.body_as_unicode())
       item = DataItem()
       for var in results:
           item['guid'] = results["guid"]
       yield item

这样做失败了

TypeError: list indices must be integers, not str

我知道我可以用

item['guid'] = results[0]["guid"]

但这只给了我整个列表的[0]索引,我想遍历所有索引。如何在列表中传递索引号?在


Tags: 文件inapijson元素列表格式framework
1条回答
网友
1楼 · 发布于 2024-10-01 02:22:49

将for循环中的results["guid"]替换为var["guid"]

for var in results:
    item['guid'] = var["guid"]
    # do whatever you want with item['guid'] here

当您可以像results[0]["guid"]那样访问guid时,这意味着您有一个字典列表,每个字典都包含名为guid的键。在for循环中,使用results(即list)而不是抛出TypeErrorvar(包含每次迭代中的每个字典),因为列表索引必须是整数而不是字符串(比如"guid")。在

更新:如果您想保存每个var["guid"]可以将它们保存在字典中,如下所示:

^{pr2}$

现在guid_holder包含所有元素。在

相关问题 更多 >