NiRK20
NiRK20

Reputation: 39

How could I read a dictionary that contains a function from a text file?

I want to read a dictionary from a text file. This dictionary seems like {'key': [1, ord('@')]}. I read about eval() and literal_eval(), but none of those two will work due to ord().

I also tried json.loads and json.dumps, but no positive results.

Which other way could I use to do it?

Upvotes: 3

Views: 76

Answers (2)

Brad Day
Brad Day

Reputation: 400

So Assuming you read the text file in with open as a string and not with json.loads you could do some simple regex searching for what is between the parenthesis of ord e.g ord('@') -> @

This is a minimal solution that reads everything from the file as a single string then finds all instances of ord and places the integer representation in an output list called ord_. For testing this example myfile.txt was a text file with the following in it

{"key": [1, "ord('@')"],

"key2": [1, "ord('K')"]}

import json
import re
with open(r"myfile.txt") as f:
    json_ = "".join([line.rstrip("\n") for line in f])

rgx = re.compile(r"ord\(([^\)]+)\)")
rgd = rgx.findall(json_)
ord_ = [ord(str_.replace(r"'", "")) for str_ in rgd]

Upvotes: 1

12944qwerty
12944qwerty

Reputation: 2007

  • json.dump() and json.load() will not work because ord() is not JSON Serializable (meaning that the function cannot be a JSON object.
  • Yes, eval is really bad practice, I would never recommend it to anyone for any use.

The best way I can think of to solve this is to use conditions and an extra list.

# data.json = {'key': [1, ['ord', '@']]}    # first one is function name, second is arg
with open("data.json") as f:
    data = json.load(f)
# data['key'][1][0] is "ord"
if data['key'][1][0] == "ord":
    res = ord(data['key'][1][1])

Upvotes: 0

Related Questions