python - 如何从包含列表的嵌套Python字典中的键中删除符号?

标签 python json dictionary nested key

我有一个包含以下结构的 n 个 JSON 对象的数据转储:

{
    "_id" : {"$numberLong" : "734702956751294464" }, 
    "created_at" : "Mon May 23 11:10:09 +0000 2016", 
    "entities" : {
        "user_mentions" : [ { 
            "name" : "Thierry Zoller", 
            "id" : 15589731, 
            "indices" : [ 3, 17 ], 
            "screen_name" : "thierryzoller", 
            "id_str" : "15589731" 
            } ], 
        "media" : [ { 
            "source_status_id" : { "$numberLong" : "734677772963041280" }, 
            "url" : "XXXXX", 
            "source_user_id_str" : "15589731", 
            "source_user_id" : 15589731, 
            "id" : { "$numberLong" : "734677772703019008" }, 
            "type" : "photo", 
            "id_str" : "734677772703019008" 
            } ], 
        "hashtags" : [] }, 
    "favorited" : false, 
    "in_reply_to_user_id_str" : null, 
    "extended_entities" : { 
        "media" : [ { 
            "source_status_id" : { "$numberLong" : "734677772963041280" }, 
            "media_url_https" : "XXXXX", 
            "url" : "XXXXX", 
            "source_user_id_str" : "15589731", 
            "source_user_id" : 15589731,
            "indices" : [ 113, 136 ], 
            "display_url" : "pic.twitter.com/nO9tw2O4eY", 
            "id" : { "$numberLong" : "734677772703019008" }, 
            }]
        }
}

我想删除“$numberLong”键中的“$”。

以下代码消除了列表外部键的“$”:

def rec_key_replace(obj):
    if isinstance(obj, Mapping):
        return {key.replace('$', ''): rec_key_replace(val) for key, val in obj.items()}
    return obj

如何扩展此函数,以便可以从键中删除所有“$”,即使它们位于嵌套列表中(列表也可能包含其他列表等)?

谢谢。

最佳答案

您可以使用递归函数来运行数据结构并替换以 '$' 开头的字典键。

  1. 如果当前对象是一个列表,则递归地遍历它所包含的项目。

  2. 如果对象是字典,则通过使用 '$' 字符设置新键来更新以 '$' 符号开头的键 剥离旧键的弹出值,然后递归字典值以发现嵌套的字典或列表。字符串值将按原样返回。

<小时/>
from pprint import pprint

def replace_keys(obj):
    if isinstance(obj, list):
        return [<b>replace_keys(x)</b> for x in obj]
    elif isinstance(obj, dict):
        return {k.lstrip('$') if k.startswith('$') else k: <b>replace_keys(x)</b> 
                                                       for k, v in obj.items()}
    else:
        return obj

new_obj = replace_keys(obj)
pprint(new_obj) 
<小时/>
{'_id': {'numberLong': '734702956751294464'},
 'created_at': 'Mon May 23 11:10:09 +0000 2016',
 'entities': {'hashtags': [],
              'media': [{'id': {'numberLong': '734677772703019008'},
                         'id_str': '734677772703019008',
                         'source_status_id': {'numberLong': '734677772963041280'},
                         'source_user_id': 15589731,
                         'source_user_id_str': '15589731',
                         'type': 'photo',
                         'url': 'XXXXX'}],
              'user_mentions': [{'id': 15589731,
                                 'id_str': '15589731',
                                 'indices': [3, 17],
                                 'name': 'Thierry Zoller',
                                 'screen_name': 'thierryzoller'}]},
 'extended_entities': {'media': [{'display_url': 'pic.twitter.com/nO9tw2O4eY',
                                  'id': {'numberLong': '734677772703019008'},
                                  'indices': [113, 136],
                                  'media_url_https': 'XXXXX',
                                  'source_status_id': {'numberLong': '734677772963041280'},
                                  'source_user_id': 15589731,
                                  'source_user_id_str': '15589731',
                                  'url': 'XXXXX'}]},
 'favorited': 'false',
 'in_reply_to_user_id_str': 'null'}

关于python - 如何从包含列表的嵌套Python字典中的键中删除符号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45151628/

相关文章:

python - 根据另一列获取一列中最常见的值/将 pandas 系列的系列转换为列表的字典

python - SQLAlchemy 找不到类名

java - 如何在单个文件java中读取包含多个内容的JSON

java - Jackson JsonMappingException 无法实例化

python - 如何在发布数据python中接收字典

javascript - 确定字符串中的组

python - keras的binary_crossentropy损失函数范围

java - 从json字符串反序列化为对象时如何忽略null?

arrays - 除非显式引用一个字典枚举键,否则编译器会报错

python - 如何在 django 表单中提交值后立即加载选项列表