【发布时间】:2017-12-22 10:15:11
【问题描述】:
我有一个包含以下结构的 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
如何扩展此功能,以便可以从键中删除所有“$”,即使它们位于嵌套列表中(可能列表还包含其他列表等)?
谢谢。
【问题讨论】:
-
你让它递归,但你只处理
Mapping类型的情况。您需要遍历该树中的其他对象和列表。
标签: python json dictionary nested key