'Convert JSON datatype to Python datatype - user selects the JSON data type

I have a use case where I am reading some data from an API call, but need to transform the data from the database into the user's chosen data type format. he conversion needs to happen in Python before sending back to user.

Json data type can be: String, Number

example:

input_dict: {"parameters": {"price": "STRING", "item": "NUMBER"}}
input_list : [{"price": 1, "item": 1}, {"price": 8.99, "item": 2, {"price": 9.99, "item": 3}] <- price and item are integers


Output_result : [{"price": "1", "item": 1}, {"price": "8.99", "item": 2, {"price": "9.99", "item": 3}] <-price converted to string as per user requirement and item stayed as is


Solution 1:[1]

One liner solution, using a small mapping dictionary to translate the values into corresponding python classes. Beware that you will need to use float() if provided number are not integers.

input_dict = {"parameters": {"price": "STRING", "item": "NUMBER"}}
input_list = [{"price": 1, "item": 1}, {"price": 8.99, "item": 2}, {"price": 9.99, "item": 3}] 

mapping = { "STRING" : str,
            "NUMBER": int}

output_list = [{ key: mapping[input_dict['parameters'][key]](value) for (key, value) in e.items()} for e in input_list ]

print(output_list)
# => [{'price': '1', 'item': 1}, {'price': '8.99', 'item': 2}, {'price': '9.99', 'item': 3}]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 piwai