处理来自REST响应的数组中的对象



我正在尝试从API获取对象数组。

我得到了一个像这样的数组:
[{
"id": 5,
"name": "John Doe",
"position": "TestEmployee",
"salary": 20000,
"managerid": 1
},
{
"id": 6,
"name": "John Smith",
"position": "TestEmployee",
"salary": 20000,
"managerid": 1
},
{
"id": 7,
"name": "John Crack",
"position": "TestEmployee",
"salary": 20000,
"managerid": 1
}]

从这些对象中,我需要根据名称找到一个并获得它的Id。在c#中,这可以通过创建一个对象列表并使用LINQ获取它来实现。

如何使用Python实现此功能?

你可以把你的字典列表变成字典的字典。

responses = [{
"id": 5,
"name": "John Doe",
"position": "TestEmployee",
"salary": 20000,
"managerid": 1
},
{
"id": 6,
"name": "John Smith",
"position": "TestEmployee",
"salary": 20000,
"managerid": 1
},
{
"id": 7,
"name": "John Crack",
"position": "TestEmployee",
"salary": 20000,
"managerid": 1
}]

然后定义函数:

def response2dict(responses):
responsedict = {}
for response in responses:
responsedict[response["name"]] = {}
for key,value in response.items():
responsedict[response["name"]][key]=value
return responsedict

responsedict = response2dict(responses)

那么你可以很容易地访问记录:

responsedict["John Doe"]

您的问题是,如何在python中通过id获得列表元素?

那么你应该对这个很好:

api_response = [
{
"id": 5,
"name": "John Doe",
"position": "TestEmployee",
"salary": 20000,
"managerid": 1,
},
{
"id": 6,
"name": "John Smith",
"position": "TestEmployee",
"salary": 20000,
"managerid": 1,
},
{
"id": 7,
"name": "John Crack",
"position": "TestEmployee",
"salary": 20000,
"managerid": 1,
},
]
def find_by_id(search_id):
for e in api_response:
if e["id"] is search_id:
return e
return None
print ( find_by_id(5) )

如果您的问题是如何解析JSON对象,请查看python标准库https://docs.python.org/3/library/json.html。

最新更新