简体   繁体   中英

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?

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 eg 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]
  • 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])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM