Reputation: 45
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.
Upvotes: 1
Views: 190
Reputation: 45
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.
Upvotes: 0
Reputation: 17291
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
Upvotes: 1