简体   繁体   English

使用 Python 从数组中的特定 JSON object 获取键的值

[英]Get value of key from specific JSON object in Array using Python

I'm new into Python and JSON and trying some things out.我是 Python 和 JSON 的新手,正在尝试一些东西。 However, I seem to be stranded not being able to get specific values for keys in a JSON file.但是,我似乎无法获得 JSON 文件中键的特定值。 Hope you can point me in the right direction.希望你能给我指出正确的方向。

Using an API I am able to load the data I need.使用 API 我能够加载我需要的数据。 In the file I need to lookup and print the number of free spots for a specific bicycle parking spot.在文件中,我需要查找并打印特定自行车停车位的空闲停车位数量。 Here is the code I have so far:这是我到目前为止的代码:

import json
import requests

data = requests.get("https://stallingsnet.nl/api/1/parkingcount/utrecht")

parkingData = json.loads(data.text)

for facility in parkingData:
    print(facility["facilityName"], facility["freePlaces"])

I can manage to print the free spots for all facilities, but how do I print the number of free spots for a specific facilityName?我可以设法打印所有设施的空闲点,但如何打印特定设施名称的空闲点数? For example for 'facilityName': 'Stationsplein'?例如对于“facilityName”:“Stationsplein”?

I tried to add:我试图添加:

for 'facilityName' == "Stationsplein":

but that did not display any results.但这没有显示任何结果。

I recommend to transform the data to a dictionary.我建议将数据转换为字典。 Then you can easily query the dictionary for specific place:然后您可以轻松地查询特定位置的字典:

import requests

parkingData = requests.get("https://stallingsnet.nl/api/1/parkingcount/utrecht").json()
data = {facility["facilityName"]: facility["freePlaces"] for facility in parkingData}

print(data.get('Stationsplein', 'N/A'))

Prints:印刷:

3933

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM