Skip to content Skip to sidebar Skip to footer

Removing Leading And Trailing Backlash In Key Value In Json Documents

I have the following JSON structure. 'bent': '{ \'ActiveT\': 6, \'ErrorM\': \'None\', \'Except\': \'None\', \'HadErr\': \'false\', \'HM\': 62

Solution 1:

Using re.sub

>>> print re.sub(r'\\(?=")', '', string)
"bent": "{
       "ActiveT": 6,
        "ErrorM": "None",
        "Except": "None",
        "HadErr": "false",
        "HM": 62,
        "NHM": 57,
        "Parameter": "14331232706",
        "ReturnCode": "3050",
        "Severity": "info",
        "Timestamp": "Tue July0209: 58: 16NZST2015",
        "TId": "9891319709",
        "UserInfo": "Unknown",
    }

Regex explanation

  • \\ Matches the \

  • (?=") Positive look ahead. Checks if the \ is followed by "

  • Replace it with empty string.


OR

Using string.replace

>>> print string.replace('\\"', '"')
"bent": "{
       "ActiveT": 6,
        "ErrorM": "None",
        "Except": "None",
        "HadErr": "false",
        "HM": 62,
        "NHM": 57,
        "Parameter": "14331232706",
        "ReturnCode": "3050",
        "Severity": "info",
        "Timestamp": "Tue July0209: 58: 16NZST2015",
        "TId": "9891319709",
        "UserInfo": "Unknown",
    }

Solution 2:

Using regular expressions here sounds like the wrong approach. If this was actual JSON data (I assume the { and } are missing from your example) the right answer is to parse it properly:

d1 = json.loads(data)
d2 = json.loads(d1['bent'])

Post a Comment for "Removing Leading And Trailing Backlash In Key Value In Json Documents"