Python 如何从json编码的对象重构命令

Python 如何从json编码的对象重构命令,python,json,parameters,Python,Json,Parameters,我希望能够通过json对方法、参数对进行编码和解码。大概是这样的: fn = 'simple_function' arg = 'blob' encoded = json.dumps([fn, arg]) decoded = json.loads(encoded) method, args = decoded fn = getattr(self, method) fn(*args) def create_call(*args): cmd = json.dumps(args) def

我希望能够通过json对方法、参数对进行编码和解码。大概是这样的:

fn = 'simple_function'
arg = 'blob'

encoded = json.dumps([fn, arg])
decoded = json.loads(encoded)

method, args = decoded
fn = getattr(self, method)
fn(*args)
def create_call(*args):
    cmd = json.dumps(args)

def load_call(cmd):
    method, optional_args = json.loads(*cmd)
    fn = getattr(object, method)
    fn(*optional_args)
但它失败了,因为python将“blob”字符串拆分为每个字符的元组(奇怪的行为)。我想如果args是一个实际的项目列表,它就可以工作。如果我们不想发送任何参数,调用一个没有参数的函数(没有足够的值来解包错误),它也会失败

如何为此构建一个非常通用的机制?我正在尝试制作一个服务器,它可以通过这种方式调用客户机上的函数,主要是因为我不知道如何做

所以,寻找一个解决方案,让我调用没有,一个或任何数量的参数的函数

理想的解决方案可能如下所示:

fn = 'simple_function'
arg = 'blob'

encoded = json.dumps([fn, arg])
decoded = json.loads(encoded)

method, args = decoded
fn = getattr(self, method)
fn(*args)
def create_call(*args):
    cmd = json.dumps(args)

def load_call(cmd):
    method, optional_args = json.loads(*cmd)
    fn = getattr(object, method)
    fn(*optional_args)

并且将不使用任何参数,一个不被*拆分为列表的单个字符串参数,或任何类型的参数列表。

您的参数是单个对象。不是名单。所以你要么

fn = 'simple_function'
arg = 'blob'

encoded = json.dumps([fn, arg])
decoded = json.loads(encoded)

method, args = decoded
fn = getattr(self, method)
fn(args) #don't try to expand the args


哪个“或”取决于您想要什么。

但是如果我有一个没有参数的函数,那么这将传递给它一个空列表。@user11177添加了一个额外的变量来支持它。