1

I'm searching for a method to escape all characters in all JSON-Keys in a JSON string that are not accepted by MongoDB (for example a . (dot)).

{"www.example.com":true}

Should become this (or any other accepted character):

{"wwwexamplecom":true} 

I've done this several times before with JavaScript. But it's my first time in python and I wonder if there is a function or library for that task? I looked through the JSON chapter of the python documentation (https://docs.python.org/2/library/json.html#) but did not find a solution to this.

Maybe someone knows the answer?

Many thanks in advance,

Daniel

Edit: I think it's more a duplicate of what @alecxe write in his answer.

Edit 2: Maybe this threat is also related How can I edit/rename keys during json.load in python?

Community
  • 1
  • 1
DaTebe
  • 702
  • 1
  • 9
  • 30

1 Answers1

1

According to this thread and the documentation, you should only worry about . and $ in the key names. Simply replace them:

key = key.replace(".", "").replace("$", "")
Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • Hi, your answer is good, but for me only the second step. I need to go through a whole JSON-String. Is there a "python way" of going through all JSON keys and then apply your method? Or do I have to build a new JSON String? – DaTebe Jun 22 '16 at 07:36