rahul verma rahul verma - 5 months ago 19
JSON Question

Unable to read regex in a JSON file as a string in Python

I need to read the below JSON file into Python with regex intact. I will be using the regular expressions in the program.

{
"Title": "Sample Compliance Check",
"Checks": {
"6": {
"+": ["^interfa.*", "^ip address 192\.168\.0"],
"description": "All interfaces with IP Address 192.168.0",
"action": "aaa new-model"
}
}
}


When I try to read this using the
json
module I get the error of invalid json.

json.decoder.JSONDecodeError: Invalid \escape:


I tried converting the backslash to double backslash

{
"Title": "Sample Compliance Check",
"Checks": {
"6": {
"+": ["^interfa.*", "^ip address 192\\.168\\.0"],
"description": "All interfaces with IP Address 192.168.0",
"action": "aaa new-model"
}
}
}


Now, it gets read in Python but I get the same output with double-backslashes.

Is there any way to encode regex in JSON and read it like it's encoded (in raw regex form)?

Answer

Raw string formatting and "normal string formatting" in python do not change the way the string is stored, but only how you can enter the string. So the following strings are both equal:

"\\a" == r"\a"

Python shows you backslashes escaped, but if you try the regex you will see that it matches what you want to match.

>>> bool(re.match("^ip address 192\\.168\\.0", "ip address 192.168.0"))
True
Comments