首页 > 解决方案 > 规范化 json 时,dicts 数组仅返回最后一个值

问题描述

我不知道为什么在这段代码中,数组返回的长度是正确的,但总是相同的结果:

预期结果:

[{
    '_uid': '1',
    'total_amount': 1,
    'employee_Email': 'one@users.com',
    'employee_Full_name': 'full_name 1'
}, {
    '_uid': '2',
    'total_amount': 2,
    'employee_Email': 'two@users.com',
    'employee_Full_name': 'full_name 2'
}, {
    '_uid': '3',
    'total_amount': 3,
    'employee_Email': 'three@users.com',
    'employee_Full_name': 'full_name 3'
}]

输出:

[{
    '_uid': '3',
    'total_amount': 3,
    'employee_Email': 'three@users.com',
    'employee_Full_name': 'full_name 3'
}, {
    '_uid': '3',
    'total_amount': 3,
    'employee_Email': 'three@users.com',
    'employee_Full_name': 'full_name 3'
}, {
    '_uid': '3',
    'total_amount': 3,
    'employee_Email': 'three@users.com',
    'employee_Full_name': 'full_name 3'
}]

输入数据:

graphql_results = [
{
    "_uid": "1",
    "total_amount": 1,
    "employee": {"Email": "one@users.com", "Full_name": "full_name 1"},
},
{
    "_uid": "2",
    "total_amount": 2,
    "employee": {"Email": "two@users.com", "Full_name": "full_name 2"},
},
{
    "_uid": "3",
    "total_amount": 3,
    "employee": {"Email": "three@users.com", "Full_name": "full_name 3"},
}
]
def normalize_json(
   data: dict, key_string: str = "", normalized_dict: dict = {}, separator: str = "_"
) -> dict:
   if isinstance(data, dict):
       for key, value in data.items():
           new_key = f"{key_string}{separator}{key}"
           normalize_json(
               data=value,
               key_string=new_key
               if new_key[: len(separator)] != separator
               else new_key[len(separator) :],
               normalized_dict=normalized_dict,
           )
   else:
       normalized_dict[key_string] = data
   return dict(normalized_dict)

normalize_json_array = [normalize_json(row) for row in graphql_results]

标签: python

解决方案


推荐阅读