解析来自多个词典Python的键值

时间:2018-06-17 16:43:23

标签: python json api parsing python-requests

我正在尝试开发一个简单的网络应用程序来提供" carpark_data"基于用户输入的" carpark_number" (例如" SK61")。我已经尝试过研究如何根据给定的关键字排序:Python dicts的值,但我已经达到了死胡同。

现在,我已经获得了以下代码块,这对我来说是一个静态网站,可以提供来自API的数据。如何为我修改此代码以便为想要抓住的用户提供服务" carpark_data"基于" carpark_number"他决定了?

# Set the request parameters
url = "https://api.data.gov.sg/v1/transport/carpark-availability"

# Do the HTTP get request
response = requests.get(url)

# Check for HTTP codes other than 200
if response.status_code != 200:
    print('Status:', response.status_code, 'Problem with the request. Exiting.')
    exit()
else:
    jack = response.json()
    daniel = jack['items'][0]["carpark_data"]
    print(json.dumps(daniel, indent=4)) #prints prettified jSON Data

示例输出:

[
  {
    "carpark_info": [
        {
          "total_lots": "100",
          "lot_type": "C",
          "lots_available": "72"
        }
    ],
    "carpark_number": "SK61",
    "update_datetime": "2018-06-16T02:47:59"
  },

  {
    "carpark_info": [
      {
        "total_lots": "100",
        "lot_type": "C",
        "lots_available": "72"
      }
    ],
    "carpark_number": "SK61",
    "update_datetime": "2018-06-16T02:47:59"
  }
]

1 个答案:

答案 0 :(得分:0)

我假设您希望能够将结果过滤到用户感兴趣的结果?如果是这样,这应该可以解决问题:

l1 = [
      {
        "carpark_info": [
            {
              "total_lots": "100",
              "lot_type": "C",
              "lots_available": "72"
            }
        ],
        "carpark_number": "SK61",
        "update_datetime": "2018-06-16T02:47:59"
      },

      {
        "carpark_info": [
          {
            "total_lots": "100",
            "lot_type": "C",
            "lots_available": "72"
          }
        ],
        "carpark_number": "SK62",
        "update_datetime": "2018-06-16T02:47:59"
      }
    ]

wanted_carpark = 'SK62'

# use get so it doesn't fail on no number
list(filter(lambda x: x.get('carpark_number', None) == wanted_carpark, l1))