首页 > 解决方案 > 从响应 python 中获取值

问题描述

我正在使用 python 请求向 URL 发出请求并获得以下响应

{
    "content": {
        "root": {
            "details":"http://localhost:8080/****/root",
            "content": {
                "A": {
                "details":"http://localhost:8080/***"
                },
                "B":{
                "details":"http://localhost:8080/***"
                },
                "C":{
                "details":"http://localhost:8080/****"
                }
            }
        }
    }
}

我想在列表中获取值 A、B、C。我怎样才能做到这一点?任何输入都会有很大帮助。

标签: pythonjsondictionary

解决方案


获取值并将其存储在列表中:

response = {
        "content":{
            "root":{
                    "details":"http://localhost:8080/****/root",
                    "content":{
                    "A":{
                        "details":"http://localhost:8080/***"
                    },
                    "B":{
                        "details":"http://localhost:8080/***"
                    },
                    "C":{
                        "details":"http://localhost:8080/***"
                    }
                }
            }
        }
    }

contents = response["content"]['root']['content']
contents_list = []

for content in contents.values():
    contents_list.append(content["details"])

print(contents_list)

输出:

['http://localhost:8080/***', 'http://localhost:8080/***', 'http://localhost:8080/***']

但是,如果您想同时获取 A、B 和 C 的键和值。试试这个:

for content in contents.values():
    for key, value in content.items():
        contents_list.append(f"{key}: {value}")

print(contents_list)

输出:

['details: http://localhost:8080/***', 'details: http://localhost:8080/***', 'details: http://localhost:8080/***']

推荐阅读