【问题标题】:Looping through JSON object with a conditional使用条件循环遍历 JSON 对象
【发布时间】:2022-01-24 19:49:29
【问题描述】:

在循环遍历此 json 对象 content 时遇到一些困难。 json文件是这样的:

[{'archived': False,
  'cache_ttl': None,
  'collection': {'archived': False,
   'authority_level': None,
   'color': '#509EE3',
   'description': None,
   'id': 525,
   'location': '/450/',
   'name': 'eaf',
   'namespace': None,
   'personal_owner_id': None,
   'slug': 'eaf'},
  'collection_id': 525,
  'collection_position': None,
  'created_at': '2022-01-06T20:51:17.06376Z',
  'creator_id': 1,
  'database_id': 4,
  }, ... ]

我想遍历列表中的每个字典,检查集合是否为空,然后对于每个集合,如果位置等于'/450/',则返回将该字典附加到列表中。

我的代码如下。

content = json.loads(res.text)
for q in content:
  if q['collection']:
    for col in q['collection']:
      if col['location'] == '/450/':
        data.append(q)
  
print(data) 

玩过它后,我不断收到ValueError: too many values to unpack (expected 2) TypeError: string indices must be integers 非常感谢对我的结构的任何帮助。

免责声明: 我之前把它写成一个列表理解,它就像一个魅力,但它不再起作用了,因为我现在需要检查collection 是否为空。 我之前是怎么写的:

content = [ x for x in content if x['collection']['location'] == '/450/']

【问题讨论】:

  • 你得到TypeError: string indices must be integers 因为col 是一个字符串,而你正在尝试做col['location']

标签: python json dictionary for-loop indices


【解决方案1】:

这应该适合你:

for q in content:
    if q['collection']['location'] == '/450/':
        data.append(q)
  
print(data)

如果您使用for 循环使用for col in q['collection'],您只需遍历q['collection'] 中的键,因此cols = ['archived', 'authority_level', ...]

【讨论】:

    【解决方案2】:

    根据您之前的列表理解,"location"q["collection"] 中的一个键。 当你写

    for col in q["collection"]
    

    您正在遍历 q["collection"] 中的键。其中一个键是"location"。您的 for 循环似乎超出了必要的迭代次数:

    if q['collection'] and "location" in q["collection"] and q["collection"]["location"]  == "/450/":
        data.append(q)
    

    【讨论】:

      【解决方案3】:

      您的代码迭代次数过多超出了需要。

      当您检查 col['location'] = "/450/" 时,错误 TypeError: string indices must be integers 出现在第二个条件语句。

      这是因为集合对象中并非所有令牌都有子对象,您可以在其中使用它们的键

      查看您的旧代码修改后的代码,以获得更深入的了解。 p>

      # Your old json datas
      content  = [{'archived': False,
        'cache_ttl': None,
        'collection': {'archived': False,
         'authority_level': None,
         'color': '#509EE3',
         'description': None,
         'id': 525,
         'location': '/450/',
         'name': 'eaf',
         'namespace': None,
         'personal_owner_id': None,
         'slug': 'eaf'},
        'collection_id': 525,
        'collection_position': None,
        'created_at': '2022-01-06T20:51:17.06376Z',
        'creator_id': 1,
        'database_id': 4,
        } ]
      
      data = []
      for q in content:
          if q['collection']:
              for col in q['collection']: 
                  if col['location'] == '/450/': # The first object in collection object is [archived] which is a string, this causes the program to throw error
                      data.append(q)
        
      print(data) 
      

      这是修改后的代码

      # Your json datas
      json_datas = [{'archived': False,
        'cache_ttl': None,
        'collection': {'archived': False,
         'authority_level': None,
         'color': '#509EE3',
         'description': None,
         'id': 525,
         'location': '/450/',
         'name': 'eaf',
         'namespace': None,
         'personal_owner_id': None,
         'slug': 'eaf'},
        'collection_id': 525,
        'collection_position': None,
        'created_at': '2022-01-06T20:51:17.06376Z',
        'creator_id': 1,
        'database_id': 4,
        } ]
      
      
      list_data = [] # Your list data in which appends the json data if the location is /450/
      
      for data in json_datas: # Getting each Json data
        if len(data["collection"]): # Continue if the length of collection is not 0 [NOTE: 0 = False, 1 or more = True]
          if data['collection']['location'] == "/450/": # Check the location
            list_data.append(data) # Append if true
      
      
      print(list_data)
      

      【讨论】:

        【解决方案4】:

        不需要遍历 collection 对象,因为它是一个字典,只需要检查 location 属性。

        此外,如果“collection”或“location”属性不存在,则使用 dict.get(key) 函数而不是 dict[key],因为如果找不到 key 和 get( ) 如果没有找到键,则返回 None 值。

        content = [{'archived': False,
                'cache_ttl': None,
                'collection': {'archived': False,
                               'authority_level': None,
                               'color': '#509EE3',
                               'description': None,
                               'id': 525,
                               'location': '/450/',
                               'name': 'eaf',
                               'namespace': None,
                               'personal_owner_id': None,
                               'slug': 'eaf'},
                'collection_id': 525,
                'collection_position': None,
                'created_at': '2022-01-06T20:51:17.06376Z',
                'creator_id': 1,
                'database_id': 4,
                },
               {'foo': None}
               ]
        
        #content = json.loads(res.text)
        data = []
        for q in content:
            c = q.get('collection')
            if c and c.get('location') == '/450/':
                data.append(q)
          
        print(data)
        

        输出:

        [{'archived': False, 'cache_ttl': None, 'collection': { 'location': '/450/', 'name': 'eaf', 'namespace': None }, ...}]
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-10-07
          • 2015-09-16
          • 1970-01-01
          • 2021-06-16
          • 2010-10-22
          • 2016-07-28
          • 2019-02-11
          相关资源
          最近更新 更多