Home > Mobile >  Python Replace string if outside double quotes else ignore
Python Replace string if outside double quotes else ignore

Time:07-14

Let's say I have a JSON with the following data:

{"name":"John", "isAdult":True, "Address":"42 True Street SomeLand"}

I only want to replace True with "True" using Python re module if it is outside double quotes if within double quotes then I want to ignore it.

Sample output:

{"name":"John", "isAdult":"True", "Address":"42 True Street SomeLand"}

CodePudding user response:

I will assume you mean this is a string:

'{"name":"John", "isAdult":True, "Address":"42 True Street SomeLand"}'

This is not valid JSON. For boolean values, JSON requires true and false to be all lower case.

The ideal solution here is to fix this at the source so that it is correct JSON. If you don't have control over that, then the simplest approach is to replace :True with :true. You can similarly do this for :False if needed. You may also need to allow for arbitrary whitespace after the :. Note that this solution is more general and avoids the need to worry about quotes.

CodePudding user response:

Thanks a lot @Code-Apprentice and @kindall for your valuable inputs, please find below the code that works:

import re

pattern = r'(?!^\\)":True'
text='{"name":"John", "isAdult":True, "Address":"42 True Street SomeLand"}'
x = re.sub(pattern,':"True"',text)
print(x)

Output:

{"name":"John", "isAdult:"True", "Address":"42 True Street SomeLand"}
  • Related