首页 > 解决方案 > 如何遍历 JSON 数组并获取本身是 JSON 对象的键的值

问题描述

我一直在尝试做一些简单但对我来说很难解决的事情!

我有一个看起来像这样的 json 对象:

   jsonObject =  {
      'attributes': {
        '192': { <--- This can be changed times to times meaning different number
          'id': '192',
          'code': 'hello',
          'label': 'world',
          'options': [
            {
              'id': '211',
              'label': '5'
            },
            {
              'id': '1202',
              'label': '8.5'
            },
            {
              'id': '54',
              'label': '9'
            },
            {
              'id': '1203',
              'label': '9.5'
            },
            {
              'id': '58',
              'label': '10'
            }
          ]
        }
      },
      'template': '12345',
      'basePrice': '51233',
      'oldPrice': '51212',
      'productId': 'hello',
    }

我想要做的是从选项中获取值(将 id 和标签都保存到列表中)

现在我只能做到:

for att, value in jsonObject.items():
     print(f"{att} - {value}"

如何获取标签和 ID?

标签: pythonjsoniterator

解决方案


您可以尝试以下代码:

attr = jsonObject['attributes']
temp = list(attr.values())[0]  # It is same as "temp = attr['192']", but you said '192' can be changed.
options = temp['options']
for option in options:
    print(f"id: {option['id']}, label: {option['label']}")

推荐阅读