【问题标题】:Iterate through Json list object - Python遍历 Json 列表对象 - Python
【发布时间】:2016-12-29 09:05:30
【问题描述】:

我有一些我想要遍历的 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,
    },

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

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

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

【问题讨论】:

  • 这不是一个有效的 json 对象。
  • 是什么让它不是一个有效的 obj?
  • 如何使用这个 obj 来遍历并找到显示名称?
  • 为什么将其称为json_objdataset?这两个变量一样吗?
  • 查看 here 为什么这不是一个有效的 JSON 对象

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


【解决方案1】:

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

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

将遍历您的 JSON 数据。

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

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

【讨论】:

  • 条目只是一个随机变量吗?
  • 是的 - 我正在遍历数据集中的每个对象['list'] - 在每个循环中,当前对象都被命名为“条目”。你可以随意称呼它。
  • @pokemongirl1234 是的。他选择了名称条目,因为列表中的每个对象都是一个条目。
【解决方案2】:

这对我有用。

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

【讨论】:

    【解决方案3】:

    您需要在循环中实际执行操作。 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()
    

    【讨论】:

      猜你喜欢
      • 2018-05-08
      • 2010-10-22
      • 2015-05-25
      • 2021-11-21
      • 2017-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-11
      相关资源
      最近更新 更多