1

jsonStr = '{"name": "John"s Garage", "company": "ABC"}'

It is a string JSON.

Need to convert to

'{"name": "John\"s Garage", "company": "ABC"}'

or

remove the double quotes entirely

'{"name": "Johns Garage", "company": "ABC"}'

import re
re.sub(r'[a-zA-Z]\"[a-zA-Z]', '', )

This does not give desired reuslt

user544079
  • 16,109
  • 42
  • 115
  • 171
  • Is that the one and only example? Because you could just do a search and replace on `John"s Garage`. If it's not the only example, then you need to describe more clearly what, exactly, the inputs are and what you expect the output to be. – JDB Feb 15 '18 at 22:17
  • I don't want to do jsonStr.replace('"', '') since I have "name": "John". That should not get replaced. Only double quotes inside the json value should get replaced Ex: "name": "John"s" should become "name": "John's" or "name": "Johns". Does that help? – user544079 Feb 15 '18 at 22:19

2 Answers2

3

With re.sub:

re.sub(r'(:\s+"[^"]*)"(?=[^"]*",)', r'\1', json_str)
re.sub(r'(:\s+"[^"]*)"(?=[^"]*",)', r'\1\"', json_str)
  • (:\s+"[^"]*) matches the portion from last : to second " and put in captured group 1

  • " matches literal ", and the zero width positive lookahead (?=[^"]*",) makes sure the match is followed by another ", immediately prior to ,

  • In the first replacement, only the captured group is kept; and in the second the captured group is followed by escaped " in the replacement

Example:

In [163]: json_str = '{"name": "John"s Garage", "company": "ABC"}'

In [164]: re.sub(r'(:\s+"[^"]*)"(?=[^"]*",)', r'\1', json_str)
Out[164]: '{"name": "Johns Garage", "company": "ABC"}'

In [165]: re.sub(r'(:\s+"[^"]*)"(?=[^"]*",)', r'\1\"', json_str)
Out[165]: '{"name": "John\\"s Garage", "company": "ABC"}'
heemayl
  • 39,294
  • 7
  • 70
  • 76
0

You can use re.sub like so:

re.sub(r'([a-zA-Z])"([a-zA-Z])', r'\1\2', input);

This will preserve any letter characters around the quote, so it won't target a double quote with a space, comma, or colon after it, for example.

I see now that you tried something similar. The difference is the capture groups, and re-inserting them with r'\1\2'

sorak
  • 2,607
  • 2
  • 16
  • 24