将Python函数存储在JSON中 [英] Store Python function in JSON

查看:55
本文介绍了将Python函数存储在JSON中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个这样的JSON文件:

Say I have a JSON file as such:

{
  "x":5,
  "y":4,
  "func" : def multiplier(a,b):
               return a*d
}

这过度简化了我想尝试做的事情,但基本上我正在尝试
将python UDF转换为JSON文件.有没有办法做到这一点,当我 做:

This over-simplifies what I want to try and do, but basically I am attempting
to story a python UDF into a JSON file. Is there a way to do this so that when I do:

with open('config.json') as f:
    data = json.load(f)

我可以访问这些值并执行类似的操作:

I can access those values and do something like:

v1, v2 = data['x'], data['y']
mult = data['func']
print(mult(v1,v2))

要获得预期的输出:20

注意:据我了解,JSON不存储函数,因此也许我可以将其存储为字符串,然后在python脚本中将字符串解析为函数?不太确定.

To get expected output: 20

NOTE: To my understanding JSON doesn't store functions, so maybe I can store it as a string, and then in my python script parse the string into a function? Not too sure.

推荐答案

如果您确实需要在外部JSON文件中存储函数,则一种解决方案是将lambda函数存储为值并使用eval函数从您的脚本中对其进行评估.

If you really need to store a function in an external JSON file, one solution could be to store a lambda function as a value and use the eval function to evaluate it from your script.

但是请注意,在代码中使用eval可能很危险,请在使用前考虑安全性(请参阅

But be aware that using eval in your code could be dangerous, please consider the security implications before using it (see this article from realpython.com).

config.json

{
  "x": 5,
  "y": 4,
  "function": "lambda x, y : x * y"
}

您的Python文件(test.py)

import json


def run():
    """Run function from JSON config."""

    with open("config.json") as f:
        data = json.load(f)

    x, y = data["x"], data["y"]
    multiplier = eval(data["function"])
    return multiplier(x, y)


if __name__ == "__main__":
   result = run()
   print(result)

演示

In[2]: ls
test.py
config.json

In[3]: import json

In[4]: def run():
  ...:     """Run function from JSON config."""
  ...: 
  ...:     with open("config.json") as f:
  ...:         data = json.load(f)
  ...: 
  ...:     x, y = data["x"], data["y"]
  ...:     multiplier = eval(data["func"])
  ...:     return(multiplier(x, y))
  ...:    

In[5]: run()
20

这篇关于将Python函数存储在JSON中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆