簡體   English   中英

Python-遍歷嵌套的json並保存值

[英]Python - iterate through nested json and save values

我有一個嵌套的JSON(API)Webstie,我想解析該項目並將其保存到文件(使用Scrapy框架)。

我想訪問給定元素的每個子元素,它們的格式如下

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

如果我將元素0展開,則會得到以下值,其中{...}會進一步擴展

id  6738
date    "2018-06-14T09:38:51"
date_gmt    "2018-06-14T09:38:51"
guid    
     rendered   "https:example.com"
modified    "2019-03-19T20:43:50"
modified_gmt    "2019-03-19T20:43:50"

現實情況如何

我如何連續訪問每個元素,首先是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]索引,我想遍歷所有索引。 如何在列表中傳遞索引號?

將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 (即列表)而不是拋出TypeErrorvar (每次迭代中包含每個詞典)的var ,因為列表索引必須是整數而不是字符串(例如"guid" )。

更新:如果要保存每個var["guid"] ,可以將其保存在這樣的字典中:

guid_holder = {"guid": []}
for var in results:
    guid_golder["guid].append(var["guid"])
for guid in guid_holder["guid"]:
    print(guid)

現在guid_holder包含所有元素。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM