如何在python中的json.load中编辑/重命名键? [英] How can I edit/rename keys during json.load in python?

查看:210
本文介绍了如何在python中的json.load中编辑/重命名键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需要加载到mongodb中的json文件(〜3Gb).不少json键包含一个. (点),这会导致加载到mongodb的操作失败.我想加载json文件,并在此过程中编辑键名,例如用空空格替换点.使用以下python代码

I have a json file ( ~3Gb ) that I need to load into mongodb. Quite a few of the json keys contain a . (dot), which causes the load into mongodb to fail. I want to the load the json file, and edit the key names in the process, say replace the dot with an empty space. Using the following python code

import json

def RemoveDotKey(dataPart):
    for key in dataPart.iterkeys():
        new_key = key.replace(".","")
        if new_key != key:
            newDataPart = deepcopy(dataPart)
            newDataPart[new_key] = newDataPart[key]
            del newDataPart[key]
            return newDataPart
    return dataPart

new_json = json.loads(data, object_hook=RemoveDotKey) 

称为RemoveDotKey的object_hook应该遍历所有键,它的键包含一个点,创建一个副本,用空格替换该点,然后返回副本.创建了dataPart的副本,因为不确定我是否可以遍历dataPart的键并同时插入/删除键值对.

The object_hook called RemoveDotKey should iterate over all the keys, it a key contains a dot, create a copy, replace the dot with a space, and return the copy. Created a copy of dataPart, since not sure if I can iterate over dataPart's keys and insert/delete key value pairs at the same time.

这里似乎有错误,其中所有带有点的json键都没有被编辑.我不太确定json.load的工作方式.也是python的新手(使用了不到一周的时间)

There seems to be an error here, all the json keys with a dot in them are not getting edited. I am not very sure how json.load works. Also am new to python ( been using it for less than a week )

推荐答案

您几乎拥有它:

import json

def remove_dot_key(obj):
    for key in obj.keys():
        new_key = key.replace(".","")
        if new_key != key:
            obj[new_key] = obj[key]
            del obj[key]
    return obj

new_json = json.loads(data, object_hook=remove_dot_key) 

您正在循环中返回字典,因此只需修改一个键即可.而且您无需复制值,只需重命名键即可.

You were returning a dictionary inside your loop, so you'd only modify one key. And you don't need to make a copy of the values, just rename the keys.

这篇关于如何在python中的json.load中编辑/重命名键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆