python - python - 联合/合并嵌套字典和列表以获取值类型
问题描述
我有这样的问题,我有一本字典:
{
"histories":[
{
"id":"22167",
"author":{
"displayName":"Mommy"
},
"items":[
{
"field":"resolution",
"fieldtype":"jira",
},
{
"field":"status",
"from":"10090",
"fromString":"Work in progress",
"to":"10001",
"toString":"Done"
}
]
},
{
"id":"22131",
"author":{
"displayName":"Daddy"
},
"created":"2020-02-28T10:04:22.433+0700",
"items":[
{
"field":"assignee",
"tmpToAccountId":"5c5c29b75bb21413fc41d39b"
},
{
"field":"status",
"fieldtype":"jira",
"fieldId":"status",
"from":"1",
"fromString":"Open",
"to":"10090",
"toString":"Work in progress"
}
]
}
]
}
我需要字典列表中所有嵌套对象/列表的键值类型映射信息对是这样的:
{
"histories":[
{
"id":str,
"author":{
"displayName":str
},
"created":str,
"items":[
{
"field":str,
"fieldtype":str,
"fieldId":str,
"from":str,
"fromString":str,
"to":str,
"toString":str,
"tmpToAccountId":str
]
}
]
}
所以我可以从这个字典中获取所有的键和值类型
如何解决这个问题呢?
解决方案
试试这个:
更新:
import json
def map_dict(dictionary):
result = {}
for key, value in dictionary.items():
if isinstance(value, dict):
result[key] = map_dict(value)
elif isinstance(value, list):
result[key] = []
result[key].append(map_dict(value[0]))
else:
result[key] = type(value).__name__
return result
def merge_dicts(*dict_args):
result = {}
for dictionary in dict_args:
for key, value in dictionary.items():
if isinstance(value, list):
merged = merge_dicts(*value)
dictionary[key].clear()
dictionary[key].append(merged)
result.update(dictionary)
return result
def merge_and_map(*dict_args):
merged = merge_dicts(*dict_args)
mapped = map_dict(merged)
return [mapped]
info["histories"] = merge_and_map(*info["histories"])
print(json.dumps(info, indent=4))
输出:
{
"histories": [
{
"id": "str",
"author": {
"displayName": "str"
},
"items": [
{
"field": "str",
"tmpToAccountId": "str",
"fieldtype": "str",
"fieldId": "str",
"from": "str",
"fromString": "str",
"to": "str",
"toString": "str"
}
],
"created": "str"
}
]
}
推荐阅读
- c# - Azure Functions 代理身份验证
- python - Django ORM:带有后续过滤的窗口函数
- javascript - 为什么这个嵌套的 ng-include 不会显示结果
- r - R - 错误:is.character(location) 不是 TRUE
- java - 任何操作系统设置都会影响 ExecutorService 吗?
- mysql - 如何计算特定日期范围的期初和期末股票
- graphql - graphql,当有“添加”和“更新”突变时如何设计输入类型?
- symfony - Symfony/Doctrine - QueryException - [语义错误] 第 0 行,'pizza-mia' 附近的第 48 列:错误:'pizza' 未定义
- sql-server - SQL isnull 因 try_cast 而失败
- ios - 当你回到前一个视图控制器时,当前视图控制器会发生什么?