我正在使用一个允许自定义字段的应用程序,但它将字段名称和字段条目保存为同一字典中的值。我有以下通过 GET 提供的 JSON 数据(我不控制数据库或数据结构)。我需要跟在前一个键值之后的键值。
我不知道从哪里开始。如果我尝试使用字符串引用,那么我有几个重复的值,因为所有内容都保存在 "id": 和 "value": 对中。
示例: 我想要客户名称,但字段“customer_name”和输入的值不是键:值对。如何解析出客户名称并将其分配给变量customerName?
<块引用>如果我运行 print(customerName),我希望输出为 CUSTOMER A。
样本数据:
"customFields": {
"string": [
{
"id": "customer_name",
"value": "CUSTOMER A"
},
{
"id": "department",
"value": "BUSINESS DEPARTMENT"
},
{
"id": "associate_alias",
"value": "jdoe1234"
},
{
"id": "manager_alias",
"value": "bob6789"
答案 0 :(得分:0)
您必须将您的响应转换为 Python dict
response = {"customFields": {
"string": [
{
"id": "customer_name",
"value": "CUSTOMER A"
},
{
"id": "department",
"value": "BUSINESS DEPARTMENT"
},
{
"id": "associate_alias",
"value": "jdoe1234"
},
{
"id": "manager_alias",
"value": "bob6789"
}]
}}
customer = {i['id']: i['value'] for i in response['customFields']['string']}
print(customer['customer_name'])