A much simpler approach than creating a new JsonDict class occurred to me last night:
Forget about json, just convert your dictionary (with pesky numeric keys) to a list of lists or a list of tuples!
Client code (concise)
data_dict = {1: "one", 2: "two"}
new_data_dict = {k:v for k,v in anvil.server.callable("test_list", list(data_dict.items()))}
Server code (concise)
@anvil.server.callable
def test_list(data_list):
data_dict = {k:v for k,v in data_list}
return list(data_dict.items())
Simples.
@bridget: This feature request now becomes almost trivial to implement… Add it as a fallback method instead of raising anvil.server.SerializationError: Cannot serialize return value from function. Cannot serialize dictionaries with keys that aren’t strings
? Or in the meantime perhaps worthy of a footnote in the Valid arguments and return values?
Client code (verbose for readability and checking output)
def dict_to_list(self):
"""Sends a list, receives a list and converts back to a dict"""
data_dict = {1: "one", 2: "two"}
print("Client Data Dict (input):", data_dict)
data_list = list(data_dict.items())
print("Client Data List (intermediate):", data_list)
new_data_dict = {k:v for k,v in anvil.server.callable("test_list", data_list)}
print("Client Data Dict (output):", data_dict)
Server code (verbose for readability and checking output)
@anvil.server.callable
def test_list(data_list):
"""Receives a list, converts to a dict, returns a list"""
print("Server Data List (input):", data_list)
data_dict = {k:v for k,v in data_list}
print("Server Data Dict (intermediate):", data_dict)
new_data_list = list(data_dict.items())
print("Server Data List (output):", data_list)
return data_list
Output
> Client Data Dict (input): {1: 'one', 2: 'two'}
> Client Data List (intermediate): [(1, 'one'), (2, 'two')]
> Server Data List (input): [[1, 'one'], [2, 'two']]
> Server Data Dict (intermediate): {1: 'one', 2: 'two'}
> Server Data List (output): [[1, 'one'], [2, 'two']]
> Client Data Dict (output): {1: 'one', 2: 'two'}
No big deal since both are iterable, but I notice that in serialisation Anvil also changes a list of tuples to a list of lists (perhaps because Anvil itself serialises using json?).