For configuration purposes, if I store an "easy" regex in a JSON
file and load it into my Python program, it works just fine.
{
"allow": ["\/word\/.*"],
"follow": true
},
If I store a more complex regex in a JSON file, the same Python program fails.
{
"allow": ["dcp\=[0-9]+\&dppp\="],
"follow": true
},
That's the code that loads my JSON file:
src_json = kw.get('src_json') or 'sources/sample.json'
self.MY_SETTINGS = json.load(open(src_json))
and the error is usually the same, pointing my online searches to the fact, that regular expressions should not be stored in JSON files.
json.decoder.JSONDecodeError: Invalid \escape: line 22 column 38 (char 801)
YAML files seem to have similar limitations, so I shouldn't got down that way I guess.
Now, I've stored my expression inside a dict in a separate file:
mydict = {"allow": "com\/[a-z]+(?:-[a-z]+)*\?skid\="}
and load it from my program file:
exec(compile(source=open('expr.py').read(), filename='expr.py', mode='exec'))
print(mydict)
Which works and would be fine with me - but it looks a bit ... special ... with exec and compile.
Is there any reason not to do it in this way? Is there a better way to store complex data structures and regular expressions in external files which I can open / use in my program code?