Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在不使用[0]的情况下打印json对象?_Python_Json - Fatal编程技术网

Python 如何在不使用[0]的情况下打印json对象?

Python 如何在不使用[0]的情况下打印json对象?,python,json,Python,Json,所以我一直在玩弄JSONA,试图打印出来,但没有任何运气。基本上,JSONI想要打印的是城市,你会在这里看到: { 'id': '5235246c-ac21a7-151128-8cd9-512512', 'type': 'Hello world', 'metadata': { 'invite_text': "A very cool text here!!", 'cityplace': [ { 'display_text': 'Stackov

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

{
  'id': '5235246c-ac21a7-151128-8cd9-512512',
  'type': 'Hello world',
  'metadata': {
    'invite_text': "A very cool text here!!",
    'cityplace': [
      {
        'display_text': 'Stackoverflow City',
      }
    ]
  }
}
对于代码,我做了一个循环,通过调用名称
test\u print
打印出来,这给了我打印出来的JSON对象

我尝试的是

print(test_print['metadata']['cityplace']['display_text'])
不幸的是,这给了我错误

所以我需要做的是:

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

现在我的问题是:有没有可能不需要添加
[0]
就可以打印出来,因为它在将来可能不总是
0

cityplace
是一个列表。使用索引

Ex:

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"])
或者迭代它

Ex:

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"])

cityplace
不是JSON。它是一个只包含一个JSON的列表。因此,您必须从中选择JSON,这当然是,
[0]
。如果列表将来有更多元素,则需要迭代

 texts = [city['display_text'] for city in test_print['metadata']['cityplace']

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

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


这可能有助于您创建关联数组。

print(test\u print['metadata']['cityplace'][0]['display\u text'])
?我不太明白您的要求。这是一个列表,如果要打印出需要使用
[0]
的第一项,如果要打印可以使用loop@Rakesh是的,我确实打印出来说它有效,但我的问题是,如果不添加[0]就可以实现它?@DanielRoseman在这种情况下如何使它循环?我不知道怎么检查名单有多长?或者..?为什么要检查它有多长?只需对测试中的项目执行
打印['metadata']['cityplace']:打印(项目['display\u text'])