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:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0