迭代Json列表对象Python

2024-09-28 22:07:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些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,但是我的代码无法识别所有不同的显示名。这是我的代码:

^{pr2}$

如何修复语句,以便成功地循环json对象?在


Tags: 代码nametest文本idjsonstatusdescription
3条回答

这是我的工作。在

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

虽然您发布的JSON是无效的,但我假设您在结尾处留下了一些东西。在

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

将循环访问您的JSON数据。在

如果要在匹配某个值的情况下执行_stuff():

^{pr2}$

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

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

应该是

^{pr2}$

相关问题 更多 >