How can I edit/rename keys during json.load in python?

前端 未结 1 986
孤城傲影
孤城傲影 2020-12-16 16:25

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

相关标签:
1条回答
  • 2020-12-16 16:54

    You almost had it:

    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.

    0 讨论(0)
提交回复
热议问题