Home > database >  how do i add a reference to a python function in a json file
how do i add a reference to a python function in a json file

Time:03-19

I have a dictionary that contains references to different functions. I was trying to make my code more readable and make it easier to add functions to this dictionary. I was trying to convert my dictionary into a .json file but it gives an error once it tries to add the function.

This is a simplified version of my code:

import json

def func1():  print("func1")
def func2():  print("func2")
def func3():  print("func3")

testDict = {
    "value1":[func1, "test1"],
    "value3":[func2, "test2"],
    "value3":[func3, "test3"],
}

with open("test.json", "w") as fw:
    json.dump(testDict, fw, indent=2)

This is the code i made to read the .json file:

with open("test.json", "r ") as fr:
    testDict2 = json.load(fr)

However when i try to create the file it stops once it reaches the reference to the first function:

{
  "value1": [

How do i fix this and is it even possible?

CodePudding user response:

No, its not straightforwardly possible. The JSON format provides no means for serializing functions. You could potentially do this by leveraging the inspect module to get the string source of a function and then eval, but that still wouldn't behave correctly in many cases, for example, when you have a captured reference to a variable in enclosing scope in your function.

It's worth noting that in general, attempts to execute serialized code present a lot of security risks. In many applications, JSON formatted input is provided by the user. Allowing the user to provide functions as input creates an arbitrary code execution vulnerability.

CodePudding user response:

According to: https://www.w3schools.com/js/js_json_datatypes.asp "In JSON, values must be one of the following data types:

  • a string
  • a number
  • an object (JSON object)
  • an array
  • a boolean
  • null

JSON values cannot be one of the following data types:

  • a function
  • a date
  • undefined"

Python functions place is in .py files, because that is where they have any meaning. JSON is supposed to be language-independant

  • Related