python - 如何在 Python 中获取解析为列表/字典的 JSON 服务器响应的详细信息
问题描述
我是 Python 新手。我一直在尝试解析作为函数参数发送的响应。
我一直在尝试将函数从 Perl 转换为 Python。
Perl 块看起来像这样:
sub fetchId_byusername
{
my ($self,$resString,$name) =@_;
my $my_id;
my @arr = @{$json->allow_nonref->utf8->decode($resString)};
foreach(@arr)
{
my %hash = %{$_};
foreach my $keys (keys %hash)
{
$my_id = $hash{id} if($hash{name} eq $name);
}
}
print "Fetched Id is : $my_id\n";
return $my_id;
解析 JSON 数据的部分让我很困扰。我如何在 python3 中编写这个。
我尝试了类似的东西
def fetchID_byUsername(self, resString, name):
arr = []
user_id = 0
arr = resString.content.decode('utf-8', errors="replace")
for item in arr:
temp_hash = {}
temp_hash = item
for index in temp_hash.keys():
if temp_hash[name] == name:
user_id = temp_hash[id]
print("Fetched ID is: {}".format(user_id))
return user_id
现在我不确定这是否是正确的方法。
json 输入类似于:
[{"id":12345,"name":"11","email":"11@test.com","groups":[{"id":6967,"name":"Test1"},{"id":123456,"name":"E1"}],"department":{"id":3863,"name":"Department1"},"comments":"111","adminUser":false},{"id":123457,"name":"1234567","email":"1234567@test.com","groups":[{"id":1657,"name":"mytest"},{"id":58881,"name":"Service Admin"}],"department":{"id":182,"name":"Service Admin"},"comments":"12345000","adminUser":true}]
提前致谢。
解决方案
首先导入 json 库并使用 json.loads() 像:
import json
x = json.loads(json_feed) #This converts the json feed to a python dictionary
print(x["key"]) #values to "key"