Save a python dictionary as a json file

Question:

I’ve a dictionary which looks like the example I’ve mentioned below. I need to save it as a json file in the same format without changing the data types to a string value so that it can be imported later on to validate the data type of the parameters used.

data = {
    'model':{
        'param1': tuple,
        'param2': tuple
    },
    'model2':{
        'param3': int,
        'param4': bool
    }
}

It is being used like this:

isinstance(some_value, data['model']['param_1'])

Here some_value is the value for which we need to check the type.

Answers:

Some of this was already covered in the comments…

Unfortunately the only data types that can be stored in a json file are those that are described in the JSON specification, which includes arrays, objects, strings, numbers, booleans and null.

When you load a json file in using pythons json module, it automatically converts certain JSON Data Types into the python equivalent. e.g. arrays turn into lists, objects turn into dicts, strings remain strings, null becomes None etc… so what you are asking is kind of impossible.

There are of course ways around this, such as instead of storing tuple which is a type object in python, you can instead store the "tuple" keyword as a string and then write some conversion logic you can run when needed.

Probably a better alternative though is to use the pickle module. The api is identical to the json module, and it can store all python data types with ease, including custom classes in most cases. Pickled files are not human readable unfortunately, but your use case doesn’t sound like that is a requirement.

Here is a link to the documentation on the pickle module.
https://docs.python.org/3/library/pickle.html

Answered By: Alexander

Instead of using a json file, I converted the nested dictionary to yaml file and then later used it to check the data types of the supplied parameters.

Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.