Store Python function in JSON

半城伤御伤魂 提交于 2020-01-16 06:57:28

问题


Say I have a JSON file as such:

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

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))

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.


回答1:


If you really need to store a function in an external json file, one turn-around will be to store a lambda function instead, and use the eval function to call it from your script. But I don't really recommend it for good practice...

config.json

{
  "x": 5,
  "y": 4,
  "func": "lambda a, b : a * b"
}

Your Python file

import json


def main():

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

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


if __name__ == "__main__":
    main()

Demo

Python 3.6.4 (v3.6.4:d48ecebad5, Dec 18 2017, 21:07:28) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin

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

In[3]: import json

In[4]: def main():
  ...: 
  ...:     with open('config.json') as f:
  ...:         data = json.load(f)
  ...: 
  ...:     v1, v2 = data['x'], data['y']
  ...: 
  ...:     multiplier = eval(data['func'])
  ...: 
  ...:     print(multiplier(v1, v2))
  ...:    

In[5]: main()
20



回答2:


Python has a built in module name marshal that can handle this.

import marshal, ujson as json

def multiplier(a, b):
    return a * b

x = {
  "x":5,
  "y":4,
  "func" : marshal.dumps(multiplier.func_code)
}

x = json.dumps(x)
print(x)

And to get it back...

x = json.loads(x)
x = marshal.loads(x['func'])
# maybe save the function name in dict
func = types.FunctionType(x, globals(), "some_func_name") 

print(func(2,4))



回答3:


Something that is worth trying is just saving it as a string.

You can do stuff like

my_func = "
def function(a,b):
   constant = {input_var}
   return a*b + constant
"
my_func.format(input_var = 5)

exec(my_func)
function(1,2) # will return 7

This will create object of the function that you can call. Not really sure what you are trying to do but creating a json file like below should give you what you want to do: (I added the 'func' wrapper because I am assuming you will have multiple functions in one JSON)

function_json = {
'func': {
    'x':5
    'y':4
    'multiplier':
'def multiplier(a,b):
    return a*b'
}

x=function_json['func']['x']
y=function_json['func']['y']
exec(function_json['func']['multiplier'])
multiplier(x,y) # will return 20

hope this helps




回答4:


I have tried out and combined solutions from ethan-kulla and eatmeimadanish

The following code works:

my_func = '''
def function(a,b):
   constant = {input_var}
   return a*b + constant
'''

exec(my_func.format(input_var=5), globals())
# For Python 3.x, use globals() to change global context
function(2,2)


来源:https://stackoverflow.com/questions/51936785/store-python-function-in-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!