In python, the json module is included in the package, but the yaml module is made by a third party. In the program I am currently writing, to absorb the difference in the environment
The behavior is adopted. Since yaml and json have similar interfaces, I treated them exactly the same as below,
try:
import yaml
with open("config.yaml") as y:
config = yaml.load("config.yaml")
except ImportError:
import json
try:
with open("config.json") as j:
config = json.load(j)
except AttributeError:
logger.error("please set config file in json or yaml !!")
raise
#Use the value of config below ...
There was a pitfall here.
In the case of yaml, the key type is automatically guessed and read, but json is always str
.
In other words, if the config file has the following contents
config.yaml
1: "hoge"
key: "fuga"
config.json
{
"1": "hoge",
"key": "fuga"
}
In either case, you can access " fuga "
withconfig ["key"]
, but"hoge"
isconfig ["1"]
for json andconfig [" for yaml. Must be accessed with 1]
.
To avoid this, give a function as a hook at json.load ()
.
def jsonkeys_to_int_always(x): #If you can set all key types to int, click here.
if isinstance(x, dict):
return {int(k):v for k,v in x.items()}
return x
def jsonkey_to_int_when_possible(x): #Click here if you want to behave in the same way as yaml
d = {}
if isinstance(x, dict):
for k,v in x.items():
try:
k = int(k)
except ValueError:
pass
d[k] = v
return d
config = json.load("config.json", object_hook=jsonkeys_to_int_when_possible)
It seems that you can absorb the difference by Specify the value in yaml, but I don't know the details.
Recommended Posts