0

I don't know why in this code the array returned the length is correct but is always the same result:

Expected result:

[{
    '_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'
}]

output:

[{
    '_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'
}]

Input data:

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]
Luke Woodward
  • 63,336
  • 16
  • 89
  • 104
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Oct 18 '21 at 09:21
  • You're using a mutable value as a default value for a function parameter (`normalized_dict`). See https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument – Luke Woodward Oct 18 '21 at 09:25

0 Answers0