-1

I need to read dict values from a config file that contain regular expressions. One solution I saw was to read as json and convert. I tried this solution but it doesn't work:

My file contains this dict:

{"my_word":"word\s"}

Then in the script:

import json

with open('config_dict.ini') as f:
    data = f.read()

js = json.loads(data)
print(js)

But I get the error "JSONDecodeError: Invalid \escape". So I tried to escape the slash:

{"my_word":"word\\s"}

And there's no error but it reads the dict as is, which isn't going to work when I use the regex.

Is there another way to read a dict? It doesn't have to include json.

Edit: I tried this solution but it doesn't work. And anyway it's going to be messy if I have to add so many escapes to the regex.

How to handle regex string in JSON file with Python

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Chuck
  • 1,061
  • 1
  • 20
  • 45
  • Does it have to be JSON? If you just read in a line of text from a file you won't need to worry about escaping etc. – match May 05 '21 at 17:12
  • @match no, that JSON solution didn't work for me. And anyway it's gonna be very messy if I have to add many escape slashes. – Chuck May 05 '21 at 17:29
  • I see solutions for ast but I am unable to pip install. Getting errors. – Chuck May 05 '21 at 17:32

1 Answers1

0

I just realized "import ast" does what I need.

Chuck
  • 1,061
  • 1
  • 20
  • 45