从 json 正文中获取元素的确切值

get exact value of elements from json body

我希望从 json 对象中提取特定值。请参阅下面的 json 正文。

json

 data.json = [
   {
      "id": 1,
      "modifiedBy": "admin",
      "fields": {
        "Application": "1",
        "Endtermin": 23011990
        }
      },
      {
      "id": 2,
      "modifiedBy": "admin",
      "fields": {
        "Application": "2",
        "Endtermin": 11021990
        }
      }
      ]

我只想以 table 形式打印列表中的 'Application',其中 table 由一行和两列组成。

应用程序 = 1、2

我在 python 中尝试过,但出现错误。 'TypeError: list indices must be integers or slices, not str'

Python

 import json
 import sys
 data = [
   {
      "id": 1,
      "modifiedBy": "admin",
      "fields": {
        "Application": "1",
        "Endtermin": 23011990
        }
      },
      {
      "id": 2,
      "modifiedBy": "admin",
      "fields": {
        "Application": "2",
        "Endtermin": 11021990
        }
      }
      ]

 json_str = json.dumps(data)

 resp = json.loads(json_str)

 print (resp)

 print (resp['Application'])

因为 data 已经是一个字典对象,你不需要 json 并且可以简单地使用列表理解作为:

apps = [elt["fields"]["Application"] for elt in data] # Output ['1', '2']

如果列表中的某些元素缺少 keys,您也可以使用 get()

apps = [elt.get("fields",{}).get("Application") for elt in data] # Output ['1', '2']