【问题标题】:How to loop through a JSON?如何循环通过 JSON?
【发布时间】:2020-10-30 22:00:18
【问题描述】:

我正在尝试遍历下面的 json,但我只得到第一项。我知道指定键 [1] 是原因。我该如何克服这个问题?

for i in testing['Items']:
     MyFunc = testing['Items'][1]['Id']
     Containers = UrlFormater(MyFunc)

JSON:

{'Items': [{'Id': 'Test1', 'Type': 'Address', 'Text': '', 
'Highlight': '', 'Description': ''}, {'Id': 'Test2', 'Type': 
'Address', 'Text': '', 'Highlight': '', 'Description': ''} 
 }]}

【问题讨论】:

  • MyFunc = i['Id']。这就是ifor i in ... 中的用途。
  • 如果不使用i,循环还有什么意义?

标签: python json loops for-loop


【解决方案1】:

当使用 for 循环遍历列表时,您会得到一个变量,在您的示例中,您将其命名为 i,它包含列表的当前元素。例如,如果您遍历列表['Berlin', 'Paris', 'Bern'] i 在第一遍中等于'Berlin',在第二遍中它等于'Paris' 并且在最后一遍中等于'Bern'。有了这些知识,您现在可以将代码重构为如下所示:

for i in testing['Items']:
    Containers = UrlFormater(i['Id'])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-19
    • 2016-07-04
    • 2020-01-12
    • 1970-01-01
    • 2012-12-08
    • 2019-12-19
    相关资源
    最近更新 更多