-2

So I have some json files which they have in certain senteces this:

"message": "Merge branch " master " of example-week-18"

And while there are double quotes inside the messages items the json gets destroyed.

So basicaly I want to use the replace() method of string but to replace the double quotes with single quotes inside the double quotes of the messages item. I guess I have to use regular expression + replace(). ?

A desired outcome would be this:

INPUT:

"message": "Merge branch " master " of example-week-18"

"message": "Don"t do it"

OUTPUT:

"message": "Merge branch ' master ' of example-week-18"

"message": "Don't do it"
Alexandre B.
  • 5,387
  • 2
  • 17
  • 40
Alexander Rika
  • 109
  • 1
  • 10
  • 1
    just escape them instead of replacing with single quotes – Kunal Mukherjee Jun 24 '19 at 14:43
  • Possible duplicate of [Python: How to escape double quote inside json string value?](https://stackoverflow.com/questions/40150405/python-how-to-escape-double-quote-inside-json-string-value) – Mike Scotty Jun 24 '19 at 14:43

1 Answers1

-1

You're right. You can combine regular expression and the replace method.

Here I use the re module to find all the message content (block after "message:" ). Then I replace the double quotes by simple quotes. Finally, I rebuild the original whole message.

Here the code:

# Import module
import re 

# Your text
message = """
"message": "Merge branch " master " of example-week-18"

"message": "Don"t do it"
"""

new_text = ""

# Select all the data after: "message":
list_message = re.findall("\"message\"\s*:\s*?(\".*)", message)

# Replace the " by ' in text message content + rebuild original row
for message in list_message:
    new_text += '"message": "' + message[1:-1].replace('"', "'") + '"\n'

print(new_text)
# "message": "Merge branch ' master ' of example-week-18"
# "message": "Don't do it"

Hope that helps !

Alexandre B.
  • 5,387
  • 2
  • 17
  • 40