代码之家  ›  专栏  ›  技术社区  ›  CDNthe2nd

如何不使用[0]打印json对象?

  •  -1
  • CDNthe2nd  · 技术社区  · 7 年前

    所以我一直在玩弄json,并试图打印出来,但没有任何运气。基本上,JSONI想要打印的是 城市地区 您将在这里看到:

    {
      'id': '5235246c-ac21a7-151128-8cd9-512512',
      'type': 'Hello world',
      'metadata': {
        'invite_text': "A very cool text here!!",
        'cityplace': [
          {
            'display_text': 'Stackoverflow City',
          }
        ]
      }
    }
    

    我所做的代码是,我做了一个循环,通过调用名称打印出来 test_print 这给了我打印出来的JSON对象。

    print(test_print['metadata']['cityplace']['display_text'])
    

    不幸的是这给了我错误

    TypeError: list indices must be integers or slices, not str
    

    所以我需要做的是:

    print(test_print['metadata']['cityplace'][0]['display_text'])
    

    现在我的问题是:是否可以打印出来而不需要添加 [0] 因为可能并不总是这样 0 未来?

    3 回复  |  直到 7 年前
        1
  •  1
  •   Rakesh    7 年前

    cityplace

    前任:

    test_print = {
      'id': '5235246c-ac21a7-151128-8cd9-512512',
      'type': 'Hello world',
      'metadata': {
        'invite_text': "A very cool text here!!",
        'cityplace': [
          {
            'display_text': 'Stackoverflow City',
          }
        ]
      }
    }
    
    print(test_print['metadata']['cityplace'][0]['display_text'])
    

    前任:

    for i in test_print['metadata']['cityplace']:
        print(i["display_text"])
    
        2
  •  1
  •   blue_note    7 年前

    你呢 cityplace 不是JSON。它是一个只包含一个JSON的列表。所以,你必须从中选择JSON,当然, [0]

     texts = [city['display_text'] for city in test_print['metadata']['cityplace']
    
        3
  •  1
  •   gubera    7 年前

    因为您使用的是索引数组,所以访问数组值的唯一方法是使用数组的索引(并且始终为0-以后不会更改)。

    可以使用关联数组来访问访问键及其值。

    link 可以帮助您创建关联数组。