Jakub Cichalewski
Jakub Cichalewski

Reputation: 53

Alternative to eval when reading json

I have a class to parse data from some online dictionaries, it reads info about word from json and then executes methods as json tells to. An example of json:

{
"functions": [
    {
        "name": "find_translations",
        "properties": {
            "only_first": false
        }
    },
    {
        "name": "find_synonyms",
        "properties": {
             "number": 5
        }
],
"word": "to exuberate",
"language": "angielski",
"target_language": "polski",
"collection": "default"
}

So, I have a class with methods find_translations and find_synonyms. And __init __ is reading the json, and I want to execute functions with parameters as in json. I could do a bunch of ifs, but it isn't scalable, I guess. I could do eval(), but it is a vulnerability. What do I do? Can I create something like a dictionary with functions?

EDIT:

Here's my class (simplified):

class Parser:
  def __init__(self, path):
    ...
    # reads data from json
    ...

    # my problem: I need to launch methods from this class
    # that were mentioned in json. In case from example, I'd launch
    self.find_translations(self)
    self.find_synonyms(self)
    # it is an example, so without parameters


def find_translations(self):
    # do something

def find_synonyms(self):
    # do something

def find_usage(self):
    # do something

Upvotes: 1

Views: 254

Answers (2)

gautamaggarwal
gautamaggarwal

Reputation: 349

You can use the getattr function to call a particular method of class like this:-

getattr(Parser, function_name_here)(arguments_here)

I think This was what you were asking for? I hope it helps.

Upvotes: 2

jpp
jpp

Reputation: 164673

Use ast.literal_eval as a safer alternative to eval:

From documentation:

ast.literal_eval: Safely evaluate an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None.

This can be used for safely evaluating strings containing Python values from untrusted sources without the need to parse the values oneself. It is not capable of evaluating arbitrarily complex expressions, for example involving operators or indexing.

Upvotes: 2

Related Questions