迭代Json列表对象 - Python

时间:2016-08-22 17:57:21

标签: python json loops python-3.x object

我想要迭代一些JSON文本,格式如下:

{
  "itemsPerPage": 45,
  "links": {
    "next": "https://www.12345.com"
  },
  "list": [
    {
      "id": "333333",
      "placeID": "63333",
      "description": " ",
      "displayName": "test-12345",
      "name": "test",
      "status": "Active",
      "groupType": "Creative",
      "groupTypeV2": "Public",
      "memberCount": 1,
    },
     {
      "id": "32423",
      "placeID": "606",
      "description": " ",
      "displayName": "test123",
      "name": "test",
      "status": "Active",
      "groupType": "Creative",
      "groupTypeV2": "Private",
      "memberCount": 1,
    },

我正在尝试遍历此列表,并获取displayName,但是我的代码无法识别所有不同的显示名称。这是我的代码:

for i in range(len(json_obj['list'])):
if (json_obj['list'][i]['displayName'] == "some id"):
    do stuff
else:
    exit()

如何修复语句,以便成功遍历json obj?

3 个答案:

答案 0 :(得分:0)

虽然您发布的JSON无效,但我会假设您最后留下了一些东西。

for entry in dataset['list']:
    print(entry['displayName'])

将遍历您的JSON数据。

如果你想要do_stuff(),如果它匹配某个值:

for entry in dataset['list']:
    if entry['displayName'] == 'test-12345':
        do_stuff()

答案 1 :(得分:0)

这对我有用。

import json
text = """{
  "itemsPerPage": 45,
  "links": {
    "next": "https://www.12345.com"
  },
  "list": [
    {
      "id": "333333",
      "placeID": "63333",
      "description": " ",
      "displayName": "test-12345",
      "name": "test",
      "status": "Active",
      "groupType": "Creative",
      "groupTypeV2": "Public",
      "memberCount": 1
    },
     {
      "id": "32423",
      "placeID": "606",
      "description": " ",
      "displayName": "test",
      "name": "test",
      "status": "Active",
      "groupType": "Creative",
      "groupTypeV2": "Private",
      "memberCount": 1
    }]}"""
data = json.loads(text)
for item in data['list']:
    if 'displayName' in item:
        print(item['displayName'])

答案 2 :(得分:0)

您需要在循环中实际执行操作。 Python依赖空格来表示块。在编写Python时,这是你不能忘记的。

for i in range(len(json_obj['list'])):
if (json_obj['list'][i]['displayName'] == "some id"):
    do stuff
else:
    exit()

应该是

for i in range(len(json_obj['list'])):
    if (json_obj['list'][i]['displayName'] == "some id"):
        do stuff
    else:
        exit()
相关问题