python - 规范化 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]
解决方案
推荐阅读
- sql - 基于自身更新列(只有一个初始值)
- python - 如何一次重命名多个变量以添加前缀 self. 在 Pycharm 中?
- bluetooth - BLE 远程睡眠模式
- mysql - 嵌套查询的查询优化 mariadb
- javascript - 将本地 blob 图像 url 上传到 php
- jhipster - 在链中添加新过滤器
- jquery - 赛普拉斯链接 DOM 元素 - 类型“JQuery”上不存在属性“then”
' - json - 关于货币的 Ruby 练习
- python - ModuleNotFoundError:没有名为“typing_extensions”的模块
- python - 使用 k-Means 聚类尝试识别 2D 异常值根本没有异常值(而不是一个)